Python多线程之Threading.Event
2013-04-24 19:17
393 查看
多线程之间的通信在任何语言一直是个难点。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秒后唤醒他们
在列举一个交通灯例子:
从上面的例子看出 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秒后唤醒他们
import threading import time class TestThread(threading.Thread): def __init__(self, name, event): super(TestThread, self).__init__() self.name = name self.event = event def run(self): print 'Thread: ', self.name, ' start at:', time.ctime(time.time()) self.event.wait() print 'Thread: ', self.name, ' finish at:', time.ctime(time.time()) def main(): event = threading.Event() threads = [] for i in range(1, 5): threads.append(TestThread(str(i), event)) print 'main thread start at: ', time.ctime(time.time()) event.clear() for thread in threads: thread.start() print 'sleep 5 seconds.......' time.sleep(5) print 'now awake other threads....' event.set() main()
在列举一个交通灯例子:
__author__ = 'gongxingfa' import threading import random import time class VehicleThread(threading.Thread): """Class representing a motor vehicle at an intersection""" def __init__(self, threadName, event): """Initializes thread""" threading.Thread.__init__(self, name=threadName) # ensures that each vehicle waits for a green light self.threadEvent = event def run(self): """Vehicle waits unless/until light is green""" # stagger arrival times time.sleep(random.randrange(1, 10)) # prints arrival time of car at intersection print "%s arrived at %s" % \ (self.getName(), time.ctime(time.time())) # wait for green light self.threadEvent.wait() # displays time that car departs intersection print "%s passes through intersection at %s" % \ (self.getName(), time.ctime(time.time())) greenLight = threading.Event() vehicleThreads = [] # creates and starts ten Vehicle threads for i in range(1, 11): vehicleThreads.append(VehicleThread("Vehicle" + str(i), greenLight)) for vehicle in vehicleThreads: vehicle.start() while threading.activeCount() > 1: # sets the Event's flag to false -- block all incoming vehicles greenLight.clear() print "RED LIGHT! at", time.ctime(time.time()) time.sleep(3) # sets the Event's flag to true -- awaken all waiting vehicles print "GREEN LIGHT! at", time.ctime(time.time()) greenLight.set() time.sleep(1)
从上面的例子看出 threading.Event 相当于贯穿多个线程之间的条件变量,用它能够很方便的来控制多个线程的行为。
相关文章推荐
- python:threading多线程模块-Event实现线程通信
- Python多线程之threading Event
- 【Python】threading.Event模块控制多线程
- Python多线程的threading Event
- python中的多线程-threading
- Python 多线程 threading和multiprocessing模块
- Python:使用threading模块实现多线程
- Python模块学习 ---- threading 多线程控制和处理
- python 多线程 Threading
- Python线程之threading.Event
- Python标准库08 多线程与同步 (threading包)
- python threading 多线程控制和处理
- python学习笔记之使用threading模块实现多线程(转)
- 通过python threading Thread理解多线程和单线程的运行机制
- Python 多线程(threading模块)
- python之多线程 threading.Lock() 和 threading.RLock()
- python:threading多线程模块-创建线程
- Python标准库08 多线程与同步 (threading包)
- Python标准库 多线程与同步 (threading包)
- Python模块学习:threading 多线程控制和处理