Python線程的Event(事件)用於主線程控制其餘線程的執行,Event主要提供了 set、wait 、clear等方法python
set(): # 將 flag設置爲 True,形象的說就是設置爲綠燈,表示能夠通行 clear(): # 將flag清除即 False,也就是說設置爲紅燈,不能通行 wait(): # 若是flag 爲 False,event.wait 就會阻塞,若是flag爲True,event.wait就通行
# 多個線程能夠等待同一個事件
有個紅燈停,綠燈行的簡單事例: 線程
# -*- coding: UTF-8 -*- import time import threading class EventThread(threading.Thread): "使用event事件讓主線程來控制其餘線程" def run(self): count = 0 event.set() # 先設置綠燈 while True: if count < 5: print("\033[42;1m green light is on...\033[0m") elif count < 10: event.clear() # 把標誌位清除,意味着變爲紅燈 print("\033[41;1m red light is on...\033[0m") else: event.set() count = 0 time.sleep(1) count += 1 class CarThread(threading.Thread): "汽車線程受紅綠燈控制" def __init__(self, name): super(CarThread, self).__init__() self.name = name def run(self): while True: if event.is_set(): # 表明綠燈 print('[%s] running...' % self.name) time.sleep(1) # 跑的進程少一些 else: print('\033[41;1m red light,cannot run...\033[0m') event.wait() # 等待標誌位設置,即等待綠燈的意思 print('\033[42;1m [%s], green light now, can run...\033[0m' % self.name) event = threading.Event() if __name__ == '__main__': light = EventThread() light.start() car_names = ['car1', 'car2', 'car3', 'car4', 'car5'] for i in range(5): car = CarThread(car_names[i]) car.start()
汽車只會在綠燈的時候跑起來blog