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() ...

Get Python Parallel Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.