threading.Event is a thread synchronization utility in Python used for communication between threads. It provides the "set", "wait", and "clear" methods to control thread execution. \n\n1. set method: Sets the internal flag of the Event object to True, notifying all waiting threads to continue execution. If no threads are waiting, the next call to the wait method will return immediately. \n\n2. wait method: Makes the current thread wait until the internal flag of the Event object is True. If the flag is True, the wait method returns immediately; otherwise, it blocks until the flag becomes True. \n\n3. clear method: Sets the internal flag of the Event object to False, causing all threads calling the wait method to be blocked. \n\nHere is an example code using threading.Event: \n\npython \nimport threading \nimport time \n\n# Create an Event object \nevent = threading.Event() \n\n# Thread function that waits for the Event object's flag to be True before continuing execution \ndef thread_func(): \n print("Thread started") \n event.wait() \n print("Thread resumed") \n\n# Create and start a thread \nthread = threading.Thread(target=thread_func) \nthread.start() \n\n# Main thread waits for a while before setting the Event object's flag to True \nprint("Main thread sleeping") \ntime.sleep(2) \nevent.set() \n\n# Wait for the thread to finish execution \nthread.join() \n \n\nIn the above example, the main thread creates an Event object, then creates and starts a child thread. The child thread will first print "Thread started", then call the event.wait() method to wait for the Event object's flag to be True. The main thread waits for 2 seconds before calling the event.set() method to set the Event object's flag to True. At this point, the child thread will continue execution and print "Thread resumed". Finally, the main thread calls thread.join() to wait for the child thread to finish execution. \n\nIt's important to note that the Event object's flag is initially False. Calling the clear() method sets the flag to False. When calling the wait() method, if the flag is False, the thread will be blocked until the flag becomes True.


原文地址: https://www.cveoy.top/t/topic/pQQH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录