What are the modules used to write multi-threaded applications in Python? I'm aware of the basic concurrency mechanisms provided by the language and also of Stackless Python, but what are their respective strengths and weaknesses?
In Python, any alive non-daemon thread blocks the main program to exit. Whereas, daemon threads themselves are killed as soon as the main program exits. In other words, as soon as the main program exits, all the daemon threads are killed.
exit() is executed from within a thread it will close that thread only.
In fact, a Python process cannot run threads in parallel but it can run them concurrently through context switching during I/O bound operations. This limitation is actually enforced by GIL. The Python Global Interpreter Lock (GIL) prevents threads within the same process to be executed at the same time.
Event can be checked via the is_set() function. The main thread, or another thread, can then set the event in order to stop the new thread from running. The event can be set or made True via the set() function. Now that we know how to stop a Python thread, let's look at some worked examples.
In order of increasing complexity:
Pros:
Cons:
In the simple use case this looks exactly like using threading
except each task is run in its own process not its own thread. (Almost literally: If you take Eli's example, and replace threading
with multiprocessing
, Thread
, with Process
, and Queue
(the module) with multiprocessing.Queue
, it should run just fine.)
Pros:
Cons:
Pros:
Cons:
In all cases I'm assuming you already understand many of the issues involved with multitasking, specifically the tricky issue of how to share data between tasks. If for some reason you don't know when and how to use locks and conditions you have to start with those. Multitasking code is full of subtleties and gotchas, and it's really best to have a good understanding of concepts before you start.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With