Foreword
Today, we're going to explore how to control the trigger execution threads.
To achieve multiple threads to control, in fact, is essentially the message communication mechanism at work, use this mechanism to send instructions that tell the thread when to be executed, when not execute, execute what.
After my summary, roughly thread communication method has the following three:
threading.Event
threading.Condition
queue.Queue
Conclusion The first throw, then we have to explore all down.
Event Event
Python provides a very simple communication mechanism Threading.Event, general condition variable. Multiple threads can wait for an event to occur, after the event, all the threads will be activated.
About Event also use super simple, just three functions
For example look at.
Execute it and see the results
After all threads are visible in the start (start ()), and is not executed, but in self.event.wait () stopped, we need to send an instruction to execute through event.set () to all threads execution down.
Condition
Condition and Event are similar, and there is not much difference.
Likewise, Condition only need to master a few functions.
For the Internet a more interesting look at an example of hide and seek
Cond communicate by blocking their own, and make each other perform. Accordingly, to achieve sequential execution.
The results look
Queue Queue
Finally to the today's hero.
The safest send data from one thread to another thread possible way is to use a queue queue library. Creating a Queue objects by multiple threads share, which threads through the use of put () and get () operation to add or delete elements in the queue.
Similarly, for the Queue, we only need to master a few functions.
Function a little more than before, but also on the other hand shows its more feature-rich.
Let me give an example of a teacher named.
Results are as follows
to sum up
Learn more than three communication methods, we can easily find and Event Condition is a native module threading module provides a simple principle, single function, it can send instructions True and False, it can only apply some simple scene in.
And Queue module is more advanced, it is possible to send any type of message, including strings, dictionaries. Its internal implementation is actually quoted Condition module (such as blocking put and get functions), it was its Condition extensions, so the more feature-rich, able to meet all applications.