背景
日常开发中使用线程池时,发现线程池里的任务异常中断/失败是不会打印错误信息的,导致结果异常还不知道发生什么
原因
ThreadpoolExecutor
线程池提交作业后,worker不会主动抛出异常。需要通过future对象的result
和exception
。ThreadpoolExecutor
对象submit()
方法提交任务后后返回future
对象。任务提交完后,得到future对象列表/字典*fn
,通过futures.as_compose(*fn)
遍历线程池中完成的task
future.expcection
遍历完成的task也就是future
对象,通过 future.exception
是否为空判断该任务是否有异常信息。
import concurrent.futures
import urllib.request
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://nonexistant-subdomain.python.org/']
# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
with urllib.request.urlopen(url, timeout=timeout) as conn:
return conn.read()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
for future in concurrent.futures.as_completed(future_to_url):
if future.exception() is not None:
print('%r generated an exception: %s' % (url, exc))
else:
print('%r page is %d bytes' % (url, len(data)))
future.result
遍历完成的task也就是future
对象,通过try except
判断 future.result()
线程的执行结果是否异常。
import concurrent.futures
import urllib.request
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://nonexistant-subdomain.python.org/']
# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
with urllib.request.urlopen(url, timeout=timeout) as conn:
return conn.read()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (url, exc))
else:
print('%r page is %d bytes' % (url, len(data)))
异常重试
- 捕获异常后,重新提交任务
....
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
executor.sumbit(load_url, url)
else:
print('%r page is %d bytes' % (url, len(data)))
- 捕获异常后,把失败task的入参保存重新执行
pending_message = []
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
pending_message.append(url)
else:
print('%r page is %d bytes' % (url, len(data)))
futures = [executor.sumbit(load_url, url) for url in pending_message]