Home  >  Article  >  Backend Development  >  Usage example code of event object using Python programming

Usage example code of event object using Python programming

高洛峰
高洛峰Original
2017-03-24 16:27:491430browse

This article mainly introduces the usage of event objects in Python programming, and analyzes the role and usage of event objects in thread communication in the form of examples. Friends in need can refer to the following

The examples in this article describe Usage of event object in Python programming. Share it with everyone 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 bit is false, the thread waits until the signal is signaled by other threads. Threads are set to true. This seems to be exactly the opposite of Windows events. The Event object implements a simple thread communication mechanism. It provides setting signals, clearing signals, waiting, etc. for realizing communication between threads.

1. Set the signal

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 flag. When the set() method of the event object 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, that is, set it to false. When the clear method of the Event is used, the isSet() method returns false

3. Waiting

The wait method of the Event object will execute quickly and complete the return only when the internal signal is true. When the internal signal flag of the Event object is false, the wait method waits until it is true before returning.

You can use Event to let the worker thread exit gracefully. The sample code is as follows:


# make thread exit nicely
class 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 the detailed content of Usage example code of event object using Python programming. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn