Executor 用于执行异步命令
submit(fn, *args, **kwargs)
执行fn(*args **kwargs) 并返回Future
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(pow, 323, 1235)
print(future.result())
map(func, *iterables, timeout=None, chunksize=1)
shutdown
ThreadPoolExecutor(max_workers=None, thread_name_prefix='', initializer=None, initargs=())
通过线程池来执行异步命令
关于死锁:
如果一个Executor调用了两次submit来执行两个任务,但这两个任务互相调用result尝试获取对方的结果,导致死锁
如果Executor工作线程只有一个,而运行的任务中又创建了一个任务,同时等待新创建的任务的result,也会死锁
ProcessPoolExecutor(max_workers=None, mp_context=None, initializer=None, initargs=())
通过进程池来执行异步命令
Future
在executor.submit时创建
cancel
cancelled
running
done
result(timeout=None)
exception(timeout=None)
add_done_callback(fn)
wait(fs, timeout=None, return_when=ALL_COMPLETED)
等待Future的结果
可等待多个
返回时根据return_when可设置返回规则
FIRST_COMPLETED FIRST_EXCEPTION ALL_COMPLETED
网友评论