Python threading模块提供Event对象用于线程间通信。它提供了一组、拆除、等待用于线程间通信的其他方法。
event它是沟通中最简单的一个过程之中,一个线程产生一个信号,号。Python 通过threading.Event()产生一个event对象。event对象维护一个内部标志(标志初始值为False),通过set()将其置为True。wait(timeout)则用于堵塞线程直至Flag被set(或者超时,可选的),isSet()用于查询标志位是否为True,Clear()则用于清除标志位(使之为False)。
举例:
下述是一段模拟“client监听并处理硬件port消息”的程序片段:硬件port消息发送时机是随机的(通过random实现),read线程负责读消息并通知parse线程去处理。
import threading import time import random L = [] def read(): count =2 while 1: count = random.randint(0,1) if count: L.append('Hello, darling,I love you ') L.append('You are so sweet~ ') if L: evt.set() print 'new rcvd sent to 'parse thread' ' time.sleep(2) print 'never here ' def parse(): while 1: if evt.isSet(): evt.clear() print repr(len(L)) +' messages to parse: ' while L: print L.pop(0) print 'all msg prased,sleep 2s ' time.sleep(2) else: print 'no message rcved ' time.sleep(2) print 'quit parse ' if __name__ == '__main__': evt = threading.Event() R = threading .Thread(target = read) P = threading .Thread(target = parse) R.start() P.start() time.sleep(2) R.join() P.join() #time.sleep(2) print 'end'
版权声明:本文博客原创文章,博客,未经同意,不得转载--“http://blog.csdn.net/suipingsp”。