Common Misconception about asyncio
suggest changeprobably the most common misconception about asyncio 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-life example is the requests library which consists, for the time being, only of blocking functions. there is no concurrency if you call any of its functions within asyncio. aiohttp on the other hand was built with asyncio in mind. its coroutines will run concurrently.
- if you have long-running CPU-bound tasks you would like to run in parallel
asynciois not for you. for pure-Python CPU work you needmultiprocessing.threadsshare the GIL, so they help only when the work releases it. - if you have IO-bound jobs running, you may run them concurrently using
asyncio.