asyncio
- This library takes advantage of two new Python reserved keywords:
asyncandawait awaitcan be thought of as an asynchronous version ofyield from, and has to be inside a coroutine- When the program reaches the
awaitstatement, the control is handed off to the event loop, which finds the next thing to run- this behaves very similarly to a
yieldin generators
- this behaves very similarly to a
Useful Functions
asyncio.runasyncio.gatherasyncio.waitasyncio.Queue
Useful Helper Libraries
aiohttpaiofilesaiomultiprocessing
concurrent.futures
Two patterns I’ve seen so far:
- Quickly toggle between multiprocessing and multithreading
with concurrent.futures.ThreadPoolExecutor as executor:
results = executor.map(fn, iterable)
with concurrent.futures.ProcessPoolExecutor as executor:
results = executor.map(fn, iterable)- Schedule buffered and concurrent pipelines
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = {executor.submit(fn, val) for val in vals}
while futures:
done, futures = concurrent.futures.wait(
futures, return_when=concurrent.futures.FIRST_COMPLETED
)
for fut in done:
pass # Do something
# Schedule additional tasks
for task in more_tasks: # `more_tasks` should be as long as `done`
future.add(executor.submit(fn, task))Note: This is also achievable using asyncio.wait