Sending events

Another way to make threads communicate is to fire events. Let me quickly show you an example of that:

# evt.py
import threading

def fire():
print('Firing event...')
event.set()

def listen():
event.wait()
print('Event has been fired')

event = threading.Event()
t1 = threading.Thread(target=fire)
t2 = threading.Thread(target=listen)
t2.start()
t1.start()

Here we have two threads that run fire and listen, respectively firing and listening for an event. To fire an event, call the set method on it. The t2 thread, which is started first, is already listening to the event, and will sit there until the event is fired. The output from the previous example is the following:

$ python evt.py
Firing event...
Event has been fired

Events are great in some situations. Think about having threads that are waiting on a connection object to be ready, before they can actually start using it. They could be waiting on an event, and one thread could be checking that connection, and firing the event when it's ready. Events are fun to play with, so make sure you experiment and think about use cases for them.

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

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