Thread synchronization with an event
Events are objects that are used for communication between threads. A thread waits for a signal while another thread outputs it. Basically, an event object manages an internal flag that can be set to true
with the set()
method and reset to false
with the clear()
method. The wait()
method blocks until the flag is true
.
How to do it…
To understand the thread synchronization through the event object, let's take a look again at the producer/consumer problem:
import time from threading import Thread, Event import random items = [] event = Event() class consumer(Thread): def __init__(self, items, event): Thread.__init__(self) self.items = items self.event = event def run(self): while True: time.sleep(2) self.event.wait() item = self.items.pop() print ('Consumer notify : %d popped from list by %s'\ %(item, self.name)) class producer(Thread...