1

I recently heard of this feature in Python3.7+ where the asyncio brought a thing called "tasks" which people refer to as background tasks. So that's may first question:

  1. Do these tasks really run in background?

Also, when comparing asyncio tasks to threads in Python, we know that python has a GIL. So, there's nothing like parallel. I know the difference in core structure i.e. asyncio tasks run in an event loop inside the same thread, while python threads are simply forked threads. But when it comes to speed, none of these are parallel.

We can call them concurrent instead. So the second question is:

  1. Which of these two would be faster?

A few things I got to know about memory consumption is:

  • Threads consume a fair amount of data since each thread needs to have its own stack. With async code, all the code shares the same stack and the stack is kept small due to continuously unwinding the stack between tasks.
  • Threads are OS structures and therefore require more memory for the platform to support. There is no such problem with asynchronous tasks.

References:

  1. What does asyncio.create_task() do?
  2. How does asyncio actually work?

Coming to my last question:

  1. When should you use asyncio tasks compared to threads? (This question has came in my mind as we can even fire async task from sync code)
Kadam Parikh
  • 378
  • 3
  • 16
  • You made two false statements about the GIL 1. Python has no GIL, the CPython has. There are other interpreters without GIL. 2. Threads can run in parallel in some situations, for example while waiting for I/O or if C code is run. – Klaus D. Feb 21 '22 at 07:16
  • Right, but most of the time, when we run Python (lang) on our system, we use the default runtime i.e. CPython. And, what you said about threads running is parallel, is could be reframed as concurrent. Parallel doesn't seem the right word. Already highlighted that in the question – Kadam Parikh Feb 21 '22 at 07:38
  • Note that the CPython and PyPy GIL can be released by native (C/RPython) code. The assertion that "none of these are parallel" is false – threads *can* run in parallel. However, ``async`` frameworks can use threads – albeit with some overhead. Whether code is faster/parallel with threads vs. async would depend on a specific application/use-case. – MisterMiyagi Feb 21 '22 at 08:59

0 Answers0