This article mainly introduces the usage of the event object of Python programming, analyzes the function and use method of event object in-line communication with the instance form, and needs the friend to refer to
The examples in this article describe the use of event objects in Python programming. Share to everyone for your reference, as follows:
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): def __init__ (self): threading. Thread.__init__ (self) def run (self): global event while True:if Event.isset (): Logging.warning (self.ge Tname () + "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 ()