Example analysis of Python programming event objects

  • 2020-05-27 05:58:17
  • OfStack

This example demonstrates the use of event objects in Python programming. I will share it with you for your reference as follows:

Python provides the Event object for thread to thread communication. It is a signal-flag set by a thread. If the signal-flag bit is false, the thread waits until the signal is set by another thread to become true. This 1 seems to be the opposite of event for windows. The Event object implements a simple thread communication mechanism, which provides setting signals, clearing signals, waiting and so on to realize the communication between threads.

1. Set the signal

Using Event's set() method, you can set the signaling flag inside the Event object to true. The Event object provides the isSet() method to determine the state of its internal signaling flags, and when the set() method of the event object is used, the isSet() method returns true.

Clear the signal

Using the clear() method of the Event object clears the signal flag inside the Event object, sets it to false, and when Event's clear method is used, the isSet() method returns false

3. Wait for

The Event object wait method only executes and returns quickly if the internal signal is true. When the internal signal flag of an Event object is false, wait method 1 waits until it is true before returning.

You can use Event to gracefully exit a worker thread, as shown in the following code:

# make thread exit nicely
class MyThread9(threading.Thread):
  def __init__(self):
  def run(self):
    global event
    while True:
      if event.isSet():
        logging.warning(self.getName() + " is Running")
        logging.warning(self.getName() + " stopped")
event = threading.Event()
def Test9():
  for i in range(6):
  for i in t1:
  q =raw_input("Please input exit:")
  if q=="q":
if __name__=='__main__':

More about Python related topics: interested readers to view this site "Python process and thread skills summary", "Python Socket programming skills summary", "Python pictures skills summary", "Python data structure and algorithm tutorial", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article has been helpful to you Python programming.

Related articles: