The events of the Python thread are used for the main thread to control the execution of other threads, and the event provides three methods wait, clear, set
Event handling mechanism: A global definition of a "flag", if the "flag" value is False, then when the program executes the Event.wait method is blocked, if the "flag" value is true, then the Event.wait method will no longer block.
- Clear: Set "Flag" to False
- Set: Sets "Flag" to True
With threading. Event implements inter-thread communication
Use Threading. Event allows a thread to wait for notifications from other threads, and we pass this event to the thread object,
Event has a flag built in by default and the initial value is false.
Once the thread enters the wait state through the Wait () method, until another thread calls the event's set () method to set the built-in flag to true,
The event notifies all waiting-state threads to resume running.
import Threading Import Time Class MyThread ( Threading. Thread): Def __init__ (self, Signal): Threading. Thread.__init__ (self) # initialize Self.singal = Signal def run (self): print "I am%s,i Would sleep ... "%self.name # into the waiting state self.singal.wait () print" I am%s, I awake ... "%self.name if __name__ = = "__main__": # initial is False Singal = threading. Event () for T in range (0, 3): thread = MyThread (Singal) Thread.Start () print "main thre Ad Sleep 3 seconds ... "Time.sleep (3) # wake-up thread with signal, waiting state singal.set ()
Import Threading def Do (event): print ' Start ' event.wait () print ' execute ' event_obj = threading . Event () for I in range: t = Threading. Thread (Target=do, args= (Event_obj,)) T.start () event_obj.clear () # continues to block INP = raw_input (' input: ') if InP = = ' true ': Event_obj.set () #唤醒
Python thread Event