python 多线程 ThreadPoolExecutor 设定超时时间跳过
时间: 2023-10-17 17:05:58 浏览: 320
可以使用 `concurrent.futures.TimeoutError` 异常来实现任务超时跳过。具体实现可以参考以下代码:
```python
import time
import concurrent.futures
def task(n):
print(f'Task {n} started')
time.sleep(n)
print(f'Task {n} completed')
return n
def main():
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
future_to_task = {executor.submit(task, n): n for n in range(1, 6)}
for future in concurrent.futures.as_completed(future_to_task, timeout=2):
try:
result = future.result()
print(f'Result from task {future_to_task[future]}: {result}')
except concurrent.futures.TimeoutError:
print(f'Task {future_to_task[future]} timed out and was skipped')
if __name__ == '__main__':
main()
```
在上述代码中,我们使用 `concurrent.futures.as_completed()` 函数来迭代每个任务的结果。我们还使用 `timeout` 参数来设定超时时间为 2 秒。如果任务超时,我们会捕获 `concurrent.futures.TimeoutError` 异常,并打印相应的提示信息。
阅读全文