Python多线程之Threading.Event

  多线程之间的通信在任何语言一直是个难点。Python提供了非常简单的通信机制 Threading.Event,通用的条件变量。多个线程可以等待某个事件的发生,在事件发生后,所有的线程都会被激活。

  Threading.Event 官方解释:

      "

This is one of the simplest mechanisms for communication between threads: one thread signals an event and other threads wait for it.

An event object manages an internal flag that can be set to true with the  set() method and reset to false with the clear() method. The wait() method blocks until the flag is true.

"

    我自己的理解就是 Event是Python多线程通信的最简单的机制之一.一个线程标识一个事件,其他线程一直处于等待状态。

    一个事件对象管理一个内部标示符,这个标示符可以通过set()方法设为True,通过clear()方法重新设为False,wait()方法则使线程一直处于阻塞状态,直到标示符变为True

   也就是说我们可以通过 以上三种方法来多个控制线程的行为。

   下面一个简单的例子,启动三个子线程,并让他们一直处于等待状态,在主线程睡眠5秒后唤醒他们

复制代码
 1 import threading
 2 import time
 3 
 4 class TestThread(threading.Thread):
 5     def __init__(self, name, event):
 6         super(TestThread, self).__init__()
 7         self.name = name
 8         self.event = event
 9     
10     def run(self):
11         print 'Thread: ', self.name, ' start at:', time.ctime(time.time())
12         self.event.wait()
13         print 'Thread: ', self.name, ' finish at:', time.ctime(time.time())
14         
15 def main():
16     event = threading.Event()
17     threads = []
18     for i in range(1, 5):
19         threads.append(TestThread(str(i), event))
20     print 'main thread start at: ', time.ctime(time.time())
21     event.clear()
22     for thread in threads:
23         thread.start()
24     print 'sleep 5 seconds.......'
25     time.sleep(5)
26     print 'now awake other threads....'
27     event.set()   
28 
29 main()
30     
复制代码

  在列举一个交通灯例子:

复制代码
 1 __author__ = 'gongxingfa'
 2 import threading
 3 import random
 4 import time
 5 
 6 
 7 class VehicleThread(threading.Thread):
 8     """Class representing a motor vehicle at an intersection"""
 9 
10     def __init__(self, threadName, event):
11         """Initializes thread"""
12 
13         threading.Thread.__init__(self, name=threadName)
14 
15         # ensures that each vehicle waits for a green light
16         self.threadEvent = event
17 
18     def run(self):
19         """Vehicle waits unless/until light is green"""
20 
21         # stagger arrival times
22         time.sleep(random.randrange(1, 10))
23 
24         # prints arrival time of car at intersection
25         print "%s arrived at %s" % \
26               (self.getName(), time.ctime(time.time()))
27 
28         # wait for green light
29         self.threadEvent.wait()
30 
31         # displays time that car departs intersection
32         print "%s passes through intersection at %s" % \
33               (self.getName(), time.ctime(time.time()))
34 
35 
36 greenLight = threading.Event()
37 vehicleThreads = []
38 
39 # creates and starts ten Vehicle threads
40 for i in range(1, 11):
41     vehicleThreads.append(VehicleThread("Vehicle" + str(i),
42                                         greenLight))
43 
44 for vehicle in vehicleThreads:
45     vehicle.start()
46 
47 while threading.activeCount() > 1:
48     # sets the Event's flag to false -- block all incoming vehicles
49     greenLight.clear()
50     print "RED LIGHT! at", time.ctime(time.time())
51     time.sleep(3)
52 
53     # sets the Event's flag to true -- awaken all waiting vehicles
54     print "GREEN LIGHT! at", time.ctime(time.time())
55     greenLight.set()
56     time.sleep(1)
复制代码

     从上面的例子看出 threading.Event  相当于贯穿多个线程之间的条件变量,用它能够很方便的来控制多个线程的行为。

posted on   Arts&Crafts  阅读(13276)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2013年4月 >
31 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 1 2 3 4
5 6 7 8 9 10 11
点击右上角即可分享
微信分享提示