The Python Threading module provides an event object for inter-thread communication, which provides methods for setting, purging, waiting, and so on to implement communication between threads. Event is one of the simplest ways of communicating between processes, one thread producing one signal and the other waiting for that signal. Python through threading. The event () generates an event object that maintains an internal flag (the flag has an initial value of false) and is set () to True,wait (timeout) to block the thread until flag is set (or timed out, optional), IsSet () used to query whether the flag bit is true,clear () is used to clear the flag bit (false).
set \ Clear Signal
The Set () method of the event sets the signal flag inside the event object to True, and the event object provides the IsSet () method to determine the state of its internal signal flag, and the IsSet () method returns true after using the set () method. The clear () method clears the signal flag inside the event object (set to False), and the IsSet () method returns false when the Clear method is used
Wait
when the internal signal flag of the event object is false, the wait method always blocks the thread from waiting until it is true or the timeout (if provided, floating-point number, in seconds) to return, and the Wait () method returns immediately if the event object's internal flag is true.
Example:
The following is a fragment of a program that simulates "client listening and processing hardware port messages": the timing of the hardware port message is random (implemented by random), and the read thread is responsible for reading the message and notifying the parse thread to process it.
Import threading Import Time import random L = [] def read (): Count =2 while 1:count = random. Randint (0,1) if Count:l.append (' Hello, Darling,i love you\n ') l.append (' Your is so Sweet~\n ') if L:evt.set () print ' new Rcvd sent to \ ' parse thread\ ' \ n ' time. Sleep (2) print ' Never here\n ' Def parse (): While 1:if Evt.isset (): Evt.clear ( ) Print repr (len (L)) + ' messages to parse:\n ' while L:print l.pop (0) print ' All msg prased,sleep 2s\n ' Time.sleep (2) else:print ' no Messag E rcved\n ' Time.sleep (2) print ' Quit parse\n ' if __name__ = = ' __main__ ': evt = threading. Event () R = Threading. Thread (target = read) P = threading. Thread (target = parse) R.start () P.start () Time.sleep (2) R.join () P.join () #time. Sleep (2) print ' End '
Python multi-thread threading Event