Given multiple threads in the program and one wants to safely communicate or exchange data between them.
Perhaps the safest way to send data from one thread to another is to use a Queue from the queue library. To do this, create a Queue instance that is shared by the threads. Threads then use
get() operations to add or remove items from the queue as shown in the code given below.
Code #1 :
Queue instances already have all of the required locking, so they can be safely shared by as many threads as per requirement. When using queues, it can be somewhat tricky to coordinate the shutdown of the producer and consumer.
A common solution to this problem is to rely on a special sentinel value, which when placed in the queue, causes consumers to terminate as shown in the code below:
Code #2 :
A subtle feature of the code above is that the consumer, upon receiving the special sentinel value, immediately places it back onto the queue. This propagates the sentinel to other consumers threads that might be listening on the same queue—thus shutting them all down one after the other.
Although queues are the most common thread communication mechanism, one can build own data structures as long as one adds the required locking and synchronization. The most common way to do this is to wrap your data structures with a condition variable.
Code #3 : Building a thread-safe priority queue
Thread communication with a queue is a one-way and non-deterministic process. In general, there is no way to know when the receiving thread has actually received a message and worked on it. However, Queue objects do provide some basic completion features, as illustrated by the
join() methods in the example given below –
Code #4 :
- Python | Communicating Between Threads | Set-2
- Releasing GIL and mixing threads from C and Python
- Python | Convert list to Python array
- Reading Python File-Like Objects from C | Python
- Important differences between Python 2.x and Python 3.x with examples
- Python | Merge Python key values to list
- Python | Index of Non-Zero elements in Python list
- Python | Sort Python Dictionaries by Key or Value
- Python | Add Logging to Python Libraries
- Python | Add Logging to a Python Script
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Visualizing O(n) using Python
- Use of min() and max() in Python
- Python Set | pop()
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.