Describing Event()
- An event is used to communicate between threads
- One thread signals an event
- Other threads wait for this event
- An
Eventinstance manages an internal flag - This internal flag represents a condition we define
- The flag can be set to
Trueusing thesetmethod - It can be reset to
Falseusing theclearmethod - The
waitmethod blocks until the flag isTrue - The
Eventconstructor creates anEventinstancee - The internal flag is set to false by default
-
An
Eventinstanceesupports the following methods:is_setsetclearwait
Describing Methods of Event Instances
clear:Resets the internal flag toFalseis_set:Returns true only if the internal flag isTrue-
set:Sets the internal flag toTrue- All threads waiting for it to become true are awakened
-
wait(timeout):Blocks until the internal flag isTrue- If the internal flag is
True, this method returns instantly -
Otherwise, it blocks until:
- Another thread calls
set - Or the optional
timeoutexpires
- Another thread calls
- If the internal flag is
Using Conditions over Events
- Typically, we'll be faced with a consumer/producer problem
-
In this scenario, we'll want to create:
- A thread as the consumer
- A thread as the producer
Eventobjects can be used to signal other threads- However, they should not be used to implement consumer/producer notification systems
- It does not work reliably because the producer might produce a new item in between the
waitandclearoperations - For these types of problems, we should prefer using
Conditioninstead - This is because
Conditionis an abstractedEvent+Lock
Example of Event
>>> from threading import Thread, Event
>>> import time
>>> start_signal = Event()
>>> def turtle():
... print('go turtle')
... time.sleep(5)
... print('signal rabbit')
... start_signal.set()
... time.sleep(10)
... print('slug done')
>>> def rabbit():
... print('rabbit waits 5 seconds')
... start_signal.wait()
... print('go rabbit')
... time.sleep(5)
... print('rabbit done')
... start_signal.clear()
>>> def race():
... t = Thread(target=turtle)
... r = Thread(target=rabbit)
... r.start()
... t.start()
>>> race()
rabbit waits 5 seconds
go turtle
signal rabbit
go rabbit
rabbit done
turtle doneReferences
Previous
Next