Intercommunication between threads

Although threads are meant to be executed independently of each other, there are many occasions in which threads need to communicate with each other, such as if a thread needs to start a task only when another thread has reached a certain point. Let's say we are dealing with a producer and consumer problem, where one thread (the producer) is responsible for putting items in the queue. The producer thread needs to send a message to the consumer thread, so that it knows that it can consume data from the queue. This can be achieved with the help of thread events in Python. Invoking threading.event() returns an event instance, which can be set using the set() method and reset using the clear() method.

In the following code block, we will see an example in which one thread will be incrementing a counter. The other thread is required to perform an action when the counter value reaches 5. It must be noted that the event also has a wait() method, which waits until the event is blocked or set. The event can wait for a timeout interval, or it can wait indefinitely, but once the set flag is true, the wait() method will not actually block the execution of the thread. This is depicted in the following code:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.122.4