probably the most common misconception about asnycio
is that it lets you run any task in parallel - sidestepping the GIL (global interpreter lock) and therefore execute blocking jobs in parallel (on separate threads). it does not!
asyncio
(and libraries that are built to collaborate with asyncio
) build on coroutines: functions that (collaboratively) yield the control flow back to the calling function. note asyncio.sleep
in the examples above. this is an example of a non-blocking coroutine that waits ‘in the background’ and gives the control flow back to the calling function (when called with await
). time.sleep
is an example of a blocking function. the execution flow of the program will just stop there and only return after time.sleep
has finished.
a real-live example is the [requests](<http://docs.python-requests.org/en/master/>)
library which consists (for the time being) on blocking functions only. there is no concurrency if you call any of its functions within asyncio
. [aiohttp](<https://aiohttp.readthedocs.io/en/stable/>)
on the other hand was built with asyncio
in mind. its coroutines will run concurrently.
asyncio
is not for you. for that you need [threads](<https://docs.python.org/3/library/threading.html?highlight=threading#module-threading>)
or [multiprocessing](<https://docs.python.org/3/library/multiprocessing.html?#module-multiprocessing>)
.asyncio
.