gpt4 book ai didi

python - 使用 ThreadPoolExecutor 强制线程超时

转载 作者:行者123 更新时间:2023-12-01 04:37:48 28 4
gpt4 key购买 nike

我正在升级我的代码以与 ThreadPoolExecuter 一起使用,并且希望能够使处理时间超过几秒的任何线程超时。是否可以对属于线程池一部分的线程强制超时?我正在使用的代码如下。

    with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
future_tasks = {executor.submit(self.crawl_task, url): url for url in self.results.keys()}

for future in concurrent.futures.as_completed(future_tasks):
url = future_tasks[future]
try:
result = future.result()
self.results[result[0]] = result[1]
except Exception as e:
print('%r generated an exception: %s' % (url, e))

我能够使线程超时的唯一方法是更改​​

for future in concurrent.futures.as_completed(future_tasks):

for future in concurrent.futures.as_completed(future_tasks, timeout=1):

但是,这将破坏整个循环,并且我将无法知道哪个线程超时以及哪些数据导致超时。

Traceback (most recent call last):
File "test.py", line 75, in <module>
request = Requests(data)
File "test.py", line 22, in __init__
for future in concurrent.futures.as_completed(future_tasks, timeout=1):
File "/source/homebrew/Cellar/python3/3.4.0_1/Frameworks/Python.framework/Versions/3.4/ lib/python3.4/concurrent/futures/_base.py", line 213, in as_completed
len(pending), len(fs)))
concurrent.futures._base.TimeoutError: 17 (of 17) futures unfinished

最佳答案

将 future 的整个 for 循环包装在异常中仍然允许其他线程结果进行处理。使用两个单独的字典,您可以查看哪些线程由于超时而停止。

with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
future_tasks = {executor.submit(self.crawl_task, url): url for url in self.requests.keys()}

try:
for future in concurrent.futures.as_completed(future_tasks, timeout=10):
result = future.result()
self.responses[result[0]] = result[1]
except Exception as e:
print(e)

timeout = [url for url in self.requests.keys() if url not in self.responses.keys()]

print('URL Threads timed out: ', timeout)

我必须指出,这违背了传统观念。通常,如果将整个 for 循环包装在异常中,则循环中异常之后的任何内容都不应处理,但 futures 的魔力似乎允许处理循环中的所有内容(超时的线程除外)。

关于python - 使用 ThreadPoolExecutor 强制线程超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31434572/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com