Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiprocessing vs multithreading vs asyncio in Python 3

I found that in Python 3.4 there are few different libraries for multiprocessing/threading: multiprocessing vs threading vs asyncio.

But I don't know which one to use or is the "recommended one". Do they do the same thing, or are different? If so, which one is used for what? I want to write a program that uses multicores in my computer. But I don't know which library I should learn.

like image 923
user3654650 Avatar asked Oct 17 '22 05:10

user3654650


People also ask

Is Asyncio multithreading or multiprocessing?

Asyncio , on the other hand, uses cooperative multitasking. The tasks must cooperate by announcing when they are ready to be switched out. That means that the code in the task has to change slightly to make this happen.

Does Asyncio use multithreading?

Instead of using Python threads to run instructions concurrently, asyncio uses an event loop to schedule instructions on the main thread. Contrasted with threads, asyncio coroutines may never be interrupted unless they explicitly yield the thread with async or await keywords.

Does Asyncio use multiprocessing?

asyncio has an API for interoperating with Python's multiprocessing library.

Which is better multiprocessing or multithreading in Python?

Multiprocessing is a easier to just drop in than threading but has a higher memory overhead. If your code is CPU bound, multiprocessing is most likely going to be the better choice—especially if the target machine has multiple cores or CPUs.


1 Answers

TL;DR

Making the Right Choice:

We have walked through the most popular forms of concurrency. But the question remains - when should choose which one? It really depends on the use cases. From my experience (and reading), I tend to follow this pseudo code:

if io_bound:
    if io_very_slow:
        print("Use Asyncio")
    else:
        print("Use Threads")
else:
    print("Multi Processing")
  • CPU Bound => Multi Processing
  • I/O Bound, Fast I/O, Limited Number of Connections => Multi Threading
  • I/O Bound, Slow I/O, Many connections => Asyncio

Reference


[NOTE]:

  • If you have a long call method (e.g. a method containing a sleep time or lazy I/O), the best choice is asyncio, Twisted or Tornado approach (coroutine methods), that works with a single thread as concurrency.
  • asyncio works on Python3.4 and later.
  • Tornado and Twisted are ready since Python2.7
  • uvloop is ultra fast asyncio event loop (uvloop makes asyncio 2-4x faster).

[UPDATE (2019)]:

  • Japranto (GitHub) is a very fast pipelining HTTP server based on uvloop.
like image 238
Benyamin Jafari Avatar answered Oct 19 '22 17:10

Benyamin Jafari