Leveraging Events
00:00 In the previous lesson, I showed you how you can use a semaphore to do resource control. In this lesson, I’ll introduce you to an inter-thread communication mechanism called events.
00:11
An event synchronization object is used to notify threads when something happens. These work like thread-safe Boolean switches. In Python, they’re found in the threading
library as the appropriately named Event
class.
00:24
An event has three key methods: .set()
is used to set the event to true, .wait()
causes a thread to wait until the event turns true, and .clear()
turns the switch back off again.
00:37 Let’s revisit our teller idea, but this time use events to control when the bank opens.
00:44
I’ve got two different Events
in this sample. One to signal the opening of the bank, and the other to signal all the tellers who have opened their windows.
00:53
The serve_customer()
call is simpler this time. Each customer blocks waiting for the bank to open. Then once it does, they block again to wait for all the tellers to open.
01:02 This time around, our tellers are magical and they can serve a customer instantaneously. Of course, you could make this more realistic by combining the semaphore idea from the previous lesson, but let’s keep it unreal. To show that each customer is blocked waiting for the event, I need to take a little time, so I’ll have the main thread sleep a bit.
01:22
Then I signal the threads using the .set()
call on the bank open event, sleep again, then signal the threads on the teller open event.
01:32 It’s time to go to the bank.
01:43 More or less self-explanatory. Every thread blocked waiting on the open bank event. Two seconds later, everyone was allowed in. Then they blocked at the open teller event and finally, two seconds later, all the customers were handled immediately.
01:58 The event isn’t the only way of signaling between threads. Next up, conditions.
Become a Member to join the conversation.