码迷,mamicode.com
首页 > 编程语言 > 详细

Python线程间事件通知

时间:2017-09-24 15:22:47      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:发送   logs   self   start   简单   --   wait   log   als   

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

 

Python线程间事件通知

标签:发送   logs   self   start   简单   --   wait   log   als   

原文地址:http://www.cnblogs.com/BGPYC/p/7587201.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!