Python programming event object usage Example Analysis, pythonevent
This example describes how to use event objects in Python programming. We will share this with you for your reference. The details are as follows:
Python provides the Event object for inter-thread communication. It is a signal flag set by the thread. If the signal flag is false, the thread waits until the signal is set by other threads to come true. This seems to be the opposite of windows event. The Event object implements a simple thread communication mechanism. It provides the setting, clearing, and waiting functions for inter-thread communication.
1. Set the signal
You can use the set () method of Event to set the signal flag inside the Event object to true. The Event object provides the isSet () method to determine the status of its internal signal signs. When the set () method of the event object is used, the isSet () method returns true.
2. Clear the signal
The clear () method of the Event object can be used to clear the signal signs inside the Event object and set it to false. When the clear method of the Event is used, the isSet () method returns false
3. Waiting
The Event object wait method can be executed quickly and returned only when the internal signal is true. When the internal signal flag of the Event object is false, the wait method will not return until it is true.
You can use Event to gracefully exit the worker thread. The sample code is as follows:
# 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.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(10) q =raw_input("Please input exit:") if q=="q": event.clear()if __name__=='__main__': Test9()