Python event mechanism
Event mechanism:
This is the simplest communication mechanism between threads: one thread sends events, other threads wait for events
The event mechanism uses an internal flag that uses the Set method to enable true, using clear to clear to false
The wait method will block the current thread knowing that the token is true
ImportQueue fromRandomImportRandint fromThreadingImportThread fromThreadingImportEventclassWritethread (Thread):def __init__(self,queue,wevent,revent): Thread.__init__(self) self.queue=queue self. Revent=revent self. Wevent=weventdefRun (self): Data= [Randint (1,10) for_inchRange (0,5)] Self.queue.put (data)Print("Send Read Event") self. Revent.set ()#-- notifies the read thread to read theSelf. Wevent.wait ()#-- wait for write events Print("recv Write Event") self. Wevent.clear ()#-Erase write events to facilitate next readclassReadthread (Thread):def __init__(Self,queue,wevent, revent): Thread.__init__(self) self.queue=queue self. Revent=revent self. Wevent=weventdefRun (self): whiletrue:self. Revent.wait ()#-- wait for the Read event Print("recv Read Event") Data=Self.queue.get ()Print("read data is {0}". Format (data)Print("Send Write Event") self. Wevent.set ()#- Send Write EventsSelf. Revent.clear ()#-Clear Read events to facilitate next readQ=queue. Queue () wevent=Event () revent=Event () wthread=Writethread (q, Wevent, revent) Rthread=Readthread (q, Wevent, revent) Wthread.start () Rthread.start ()
Results:
is [9, 4, 8, 3, 5]send write Eventrecv write Event
Python inter-thread event notification