zoukankan      html  css  js  c++  java
  • Python线程间事件通知

    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
  • 相关阅读:
    配置Python3 Pip3环境变量
    超级搜索术-读书笔记
    技术笔记-图片管理器
    Python不错的资料、网站
    输入法9键 VS 26键,哪个更适合?
    超级搜索术-思维导图
    Linux知识-Docker
    Python知识体系-基础知识03-函数/类/模块
    js基础(BOM对象)
    js基础(事件)
  • 原文地址:https://www.cnblogs.com/BGPYC/p/7587201.html
Copyright © 2011-2022 走看看