分享

Python线程间事件通知

 yydy1983 2019-08-18

Python事件机制

事件机制:
这是线程间最简单的通信机制:一个线程发送事件,其他线程等待事件
事件机制使用一个内部的标志,使用set方法进行使能为True,使用clear清除为false
wait方法将会阻塞当前线程知道标记为True

复制代码
import queue
from random import randint
from threading import Thread
from threading import Event

class WriteThread(Thread):
    def __init__(self,queue,WEvent,REvent):
        Thread.__init__(self)
        self.queue = queue
        self.REvent = REvent
        self.WEvent = WEvent

    def run(self):
            data = [randint(1,10) for _ in range(0,5)]
            self.queue.put(data)
            print("send Read Event")
            self.REvent.set()  #--> 通知读线程可以读了
            self.WEvent.wait() #--> 等待写事件
            print("recv write Event")
            self.WEvent.clear() #-->清除写事件,以方便下次读取

class ReadThread(Thread):
    def __init__(self,queue,WEvent, REvent):
        Thread.__init__(self)
        self.queue = queue
        self.REvent = REvent
        self.WEvent = WEvent
    def run(self):
        while True:
            self.REvent.wait() #--> 等待读事件
            print("recv Read Event")
            data  = self.queue.get()
            print("read data is {0}".format(data))
            print("Send Write Event")
            self.WEvent.set()  #--> 发送写事件
            self.REvent.clear() #--> 清除读事件,以方便下次读取

q= queue.Queue()
WEvent = Event()
REvent = Event()
WThread = WriteThread( q, WEvent, REvent)
RThread = ReadThread(q, WEvent, REvent)

WThread.start()
RThread.start()
复制代码

结果:

send Read Event
recv Read Event
read data is [9, 4, 8, 3, 5]
Send Write Event
recv write Event

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多