pythonpython-asynciogil

why write async code in python while GIL exists?


I am wondering, if python GIL allow only a single thread / process to run at once, why should I use asyncio, I get that switching between threads is expensive but, thats it? this is the only advantage of asyncio in python?


Solution

  • Threading in Python is inefficient because of the GIL (Global Interpreter Lock) which means that multiple threads cannot be run in parallel as you would expect on a multi-processor system. Plus you have to rely on the interpreter to switch between threads, this adds to the inefficiency.

    asyc/asyncio allows concurrency within a single thread. This gives you, as the developer, much more fine grained control of the task switching and can give much better performance for concurrent I/O bound tasks than Python threading.

    The 3rd approach that you don't mention is multiprocessing. This approach uses processes for concurrency and allows programs to make full use of hardware with multiple cores.