先看下官方介紹python
The asynchronous execution can be performed with threads, using ThreadPoolExecutor, or separate processes, using ProcessPoolExecutor. Both implement the same interface, which is defined by the abstract Executor class.
重點是 asynchronous
json
with ThreadPoolExecutor(max_workers=1) as executor: future = executor.submit(pow, 323, 1235) print(future.result())
相似於 map(內置函數)async
In [26]: def test(item): ...: print("echo", item) ...: return item ...: In [27]: list(map(test, range(10))) echo 0 echo 1 echo 2 echo 3 echo 4 echo 5 echo 6 echo 7 echo 8 echo 9 Out[27]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def test(item): print(f"echo {item}") return item with ThreadPoolExecutor(max_workers=1) as executor: future = executor.map(test, range(3))
# todo
在 IO 密集型下使用 ThreadPoolExecutor
函數
exector = ThreadPoolExecutor(max_workers=10) f: Future = exector.submit(test, 1) exception: Exception = f.exception(timeout=None)
def callback(*args): print(args) # (<Future at 0x102bcb898 state=finished raised KeyError>,) 即 f exector = ThreadPoolExecutor(max_workers=10) f: Future = exector.submit(test, 1) f.add_done_callback(callback)