This article mainly introduces the usage of event objects in Python programming, and analyzes the functions and usage of event object online communication in the form of examples, for more information about how to use the event object in Python programming, see the next article. This article analyzes the functions and usage of the event object in the event object online program communication in the form of examples, for more information, see
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()
The above is a detailed explanation of the Python instance for event object usage. For more information, see other related articles in the first PHP community!