Python 如何在ThreadPoolExecutor中为子线程设置超时?
我想为使用Python 如何在ThreadPoolExecutor中为子线程设置超时?,python,multithreading,Python,Multithreading,我想为使用executor.submit创建的每个子线程设置一个超时 我尝试了以下解决方案,但似乎不起作用。有什么建议吗 futures = [] with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor: for element in collection.find(): future = executor.submit(function) futures.append
executor.submit创建的每个子线程设置一个超时
我尝试了以下解决方案,但似乎不起作用。有什么建议吗
futures = []
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
for element in collection.find():
future = executor.submit(function)
futures.append(future)
for future in concurrent.futures.as_completed(futures):
try:
future.result(timeout=300)
except concurrent.futures.TimeoutError:
print('timeout')
pass
的文档提供了一个迭代器,该迭代器生成“它们已完成”的未来。我认为您所追求的是调用future.result
,方法是直接返回futures
数组(这样您就不会等待它们完成),并且在释放执行者之前:
futures=[]
以concurrent.futures.ThreadPoolExecutor(max_workers=10)作为执行器:
对于集合中的元素。查找()
future=执行者提交(函数)
futures.append(未来)
对于未来:
尝试:
future.result(超时=300)
除concurrent.futures.TimeoutError外:
打印('超时')
通过
的文档提供了一个迭代器,该迭代器生成“它们已完成”的未来。我认为您所追求的是调用future.result
,方法是直接返回futures
数组(这样您就不会等待它们完成),并且在释放执行者之前:
futures=[]
以concurrent.futures.ThreadPoolExecutor(max_workers=10)作为执行器:
对于集合中的元素。查找()
future=执行者提交(函数)
futures.append(未来)
对于未来:
尝试:
future.result(超时=300)
除concurrent.futures.TimeoutError外:
打印('超时')
通过