Python inter-thread event notification

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.