Python provides the event object for inter-thread communication, which is a signal flag set by the thread, and if the signal flag bit is false, the thread waits until the signal is set to true by another thread. This seems to be the exact opposite of Windows's event. The event object implements a simple threading mechanism that provides the setup signal, clears the signal, waits, and so on to implement the communication between threads.
1. Setting the Signal
Use the Set () method of the event to set the signal token inside the event object to be true. The event object provides the IsSet () method to determine the state of its internal signal flag, and when the event object's set () method is used, the IsSet () method returns True.
2. Clear the Signal
Use the Clear () method of the event object to clear the signal flag inside the event object and set it to false, and when the clear method of the event is used, the IsSet () method returns a false
3. Wait
The event object Wait method only executes quickly and completes the return if the internal signal is true. When an event object's internal signal flag is false, the wait method waits until it is true to return. You can use the event to gracefully exit the worker thread, as shown in the following example code:
# Make thread exit Nicelyclass MyThread9 (threading. Thread):d EF __init__ (self): threading. Thread.__init__ (self) def run (self): global eventwhile true:if event.isset (): Logging.warning (Self.getname () + ' is Running ") Time.sleep (2) else:logging.warning (Self.getname () +" stopped ") Break;event = Threading. Event () Event.set () def Test9 (): T1=[]for I in range (6): T1.append (MYTHREAD9 ()) for I in T1:i.start () Time.sleep (TEN) Q =raw_ Input ("Please input exit:") if q== "Q": Event.clear () if __name__== ' __main__ ': Test9 ()
Python Learning Note Four---Use of event