我正在由3个工作人员创建线程池,并为执行程序分配10个任务。
我执行任务时没有任何输出。
from concurrent.futures import ThreadPoolExecutor
import threading
import random
def task(n):
import sleep
sleep.time(5)
print("Processing {}".format(n))
def main():
executor = ThreadPoolExecutor(max_workers=3)
for each in range(10):
executor.submit(task, each)
if __name__ == '__main__':
main()
答案 0 :(得分:1)
尝试在函数中导入sleep
时,会遇到ImportError异常。
将功能更改为
import time
def task(n):
time.sleep(3)
print("Processing {}".format(n))
如果您想查看这些错误(来自原始task
),请更改main
以累积期货并将其退还。然后遍历期货并打印结果。
...
def main():
executor = ThreadPoolExecutor(max_workers=3)
futures = []
for each in range(10):
futures.append(executor.submit(task, each))
return futures
if __name__ == '__main__':
futures = main()
for future in futures:
print(future, future.exception())
会产生这样的东西
>>>
<Future at 0x34712d0 state=finished raised ImportError> No module named 'sleep'
<Future at 0x34b0e70 state=finished raised ImportError> No module named 'sleep'
<Future at 0x34b0ff0 state=finished raised ImportError> No module named 'sleep'
<Future at 0x34be170 state=finished raised ImportError> No module named 'sleep'
<Future at 0x34be1f0 state=finished raised ImportError> No module named 'sleep'
<Future at 0x34be270 state=finished raised ImportError> No module named 'sleep'
<Future at 0x34be2f0 state=finished raised ImportError> No module named 'sleep'
<Future at 0x34be370 state=finished raised ImportError> No module named 'sleep'
<Future at 0x34be3f0 state=finished raised ImportError> No module named 'sleep'
<Future at 0x34be470 state=finished raised ImportError> No module named 'sleep'
>>>
答案 1 :(得分:0)
为补充wwii的答案,在使用ThreadPoolExecutor
之前,我建议首先使用普通线程进行测试。
由于ThreadPoolExecutor
旨在在您想要获得结果(future.result()
)时引发异常,但是有时我们甚至不关心结果。在这种情况下,任务将隐式失败,而不会发出任何通知。