Concurrent Programming Python thread message communication mechanism to coordinate tasks

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


13717038-d7097f0d5dda9735.png

For example look at.


13717038-403b7e6352c55e2f.png

Execute it and see the results


13717038-f208982bd406ca82.png

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.


13717038-41946f75c2a32417.png

For the Internet a more interesting look at an example of hide and seek


13717038-f3ff83ae0e0037ea.png

Cond communicate by blocking their own, and make each other perform. Accordingly, to achieve sequential execution.

The results look


13717038-de2b74c2b3302759.png


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.


13717038-2de9e67d2ade0db8.png

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.


13717038-183ee5a86044b75c.png

Results are as follows


13717038-bff12c847798f20a.png


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.

Guess you like

Origin blog.csdn.net/weixin_34088583/article/details/91001244
Recommended