# !/usr/bin/python
# -*- coding:utf-8 -*-
# ++++++++++++++++++++
# author: FMspider
# time: 2018-5-3 17:16
# function: 同步条件(Event) 条件同步和条件变量同步差不多意思,只是少了锁功能,因为条件同步设计于不访问共享资源的
# 条件环境。event = threading.Event():条件环境对象,初始值为False。
# event.siSet():返回event的状态值
# event.wait(): 返回event.isSet() == False装阻塞线程
# event.set(): 设置event的状态值为TRUE,所有阻塞池的线程激活进入就绪状态,等待操作系统调试
# event.clear(): 恢复event的状态值为False
import time
import threading
class Boss(threading.Thread):
def run(self):
print("BOSS:今晚需要加班22:00.")
event.isSet() or event.set()
time.sleep(5)
print("22:00 BOSS: 可以下班了。")
event.isSet() or event.set()
class Worker(threading.Thread):
def run(self):
event.wait()
print("Worker: 哎。命苦啊!")
time.sleep(1)
event.clear()
event.wait()
print("Worker: ohYeah!")
if __name__ == '__main__':
event = threading.Event()
threads = []
for i in range(5):
threads.append(Worker())
threads.append(Boss())
for t in threads:
t.start()
for t in threads:
t.join()
python 线程之同步条件(Event)
最新推荐文章于 2023-07-17 10:47:17 发布