Async Options
concurrent.futures
(thread pooling)threading
multiprocessing
asyncio
Asyncio
Why asyncio?
Well, Global Interpreter Lock aka GIL was introduced to make CPython’s memory handling easier and to allow better integrations with C (for example the extensions). The GIL is a locking mechanism that the Python interpreter runs only one thread at a time. Multiple process work, but are expensive.
The revolution is the event loop. An event loop basically waits for something to happen and then acts on the event. The event loop tracks different I/O events and switches to tasks which are ready and pauses the ones which are waiting on I/O. Thus we don’t waste time on tasks which are not ready to run right now. Single threaded, but gives apperance of parallelism through waiting on I/O.
Background
As of 9/8/18, async doesn't work very well in jupyter notebooks(probs displaying errors and underlying event loop already running)
Async python stand library, new in py version 3.4
Uses coroutines which allow a ft to return without losing its state i.e python yielding iterators. Difference with threads is these are collaborative and only one coroutine run at a time, while threads are parallel
ask is a wrapper for a coroutine and a subclass of Future.
Async/Await
Python has native support for async functions defining a coroutine. Calling these functions doesn't run the code, but returns a JS promise-like coroutine object
To actually call these fts, use await
inside another ft
Event Loop
To add something to event loop
Important Fts
Async For/With
Async for
Allows other coroutines to take turns inbetween loops
Tasks
These let you return values from a sync ft and ??
Example
We use aiohttp
for async requests, if we just used urllib or something then this whole async thing wouldn't be helpful.
Writing is still sync, but could use async file io lib
Last updated