• python 线程间事件通知


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

     1 import queue
     2 from random import randint
     3 from threading import Thread
     4 from threading import Event
     5 
     6 class WriteThread(Thread):
     7     def __init__(self,queue,WEvent,REvent):
     8         Thread.__init__(self)
     9         self.queue = queue
    10         self.REvent = REvent
    11         self.WEvent = WEvent
    12 
    13     def run(self):
    14             data = [randint(1,10) for _ in range(0,5)]
    15             self.queue.put(data)
    16             print("send Read Event")
    17             self.REvent.set()  #--> 通知读线程可以读了
    18             self.WEvent.wait() #--> 等待写事件
    19             print("recv write Event")
    20             self.WEvent.clear() #-->清除写事件,以方便下次读取
    21 
    22 class ReadThread(Thread):
    23     def __init__(self,queue,WEvent, REvent):
    24         Thread.__init__(self)
    25         self.queue = queue
    26         self.REvent = REvent
    27         self.WEvent = WEvent
    28     def run(self):
    29         while True:
    30             self.REvent.wait() #--> 等待读事件
    31             print("recv Read Event")
    32             data  = self.queue.get()
    33             print("read data is {0}".format(data))
    34             print("Send Write Event")
    35             self.WEvent.set()  #--> 发送写事件
    36             self.REvent.clear() #--> 清除读事件,以方便下次读取
    37 
    38 q= queue.Queue()
    39 WEvent = Event()
    40 REvent = Event()
    41 t1= WriteThread( q, WEvent, REvent)
    42 t2 = ReadThread(q, WEvent, REvent)
    43 
    44 t1.start() 
    45 t2.start()
  • 相关阅读:
    CentOS系统下的数据盘挂载
    在iOS微信浏览器中自动播放HTML5 audio(音乐)的2种正确方式
    C盘占用过满问题
    大量ECAgent报错
    微信电脑版不断崩溃
    java web 在tomcat没有正常输出
    文件解压缩失败
    在myeclipse安装beyond插件
    限时免费 GoodSync 10 同步工具【转】
    soapUI的bug切换版本解决
  • 原文地址:https://www.cnblogs.com/zenan/p/8629835.html
Copyright © 2020-2023  润新知