The Python Threading module provides an event object for inter-thread communication. It provides a set of other methods for removing and waiting for inter-thread communication.
Event it is the simplest process of communication in which a thread produces a signal, a number. Python through threading. Event () produces an event object. The event object maintains an internal flag (the flag has an initial value of false) and sets it to true through set (). Wait (timeout) is used to block the thread until flag is set (or timeout, optional), and IsSet () is used to clear the flag bit (to false) if the query flag bit is True,clear ().
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 infer 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 (set to false) inside the event object. After using the clear method. The IsSet () method returns false
Wait
when the internal signal flag of the event object is false. The wait method always blocks the thread waiting for it to be true or 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 handling hardware port messages": Hardware port Message timing is random (implemented by random), 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 '
Copyright notice: This article blog original article, blog, without consent, not reproduced--"HTTP://BLOG.CSDN.NET/SUIPINGSP".
Python Multi-threaded threading Event