040同步条件event
2024-10-22 13:33:34
条件同步和条件变量同步差不多意思,只是少了锁功能,因为条件同步设计于不访问共享资源的条件环境,event=threading.Event():条件环境对象,初始值为False.
event.isSet(): 返回event的状态值
event.wait(): 如果event.isSet()==False将阻塞线程
event.set(): 设置event的状态值为True,所有阻塞池的线程激活进入就绪状态,等待操作系统调度
event.clear(): 恢复event的状态值为False
import time,threading class Boss(threading.Thread):
def run(self):
print('Boss:今晚加班到22:00')
event.isSet()or event.set()
time.sleep(5)
print('Boss:<22:00>可以下班了')
event.isSet()orevent.set() class Worker(threading.Thread):
def run(self):
event.wait()
print('Worker:命苦啊~')
time.sleep(0.25)
event.clear()
event.wait()
print('Worker:oh,yeah') 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()
import threading,time
import random
def light():
if not event.isSet():
event.set() #wait就不阻塞 #绿灯状态
count = 0
while True:
if count < 10:
print('\033[42;1m--green light on---\033[0m')
elif count <13:
print('\033[43;1m--yellow light on---\033[0m')
elif count <20:
if event.isSet():
event.clear()
print('\033[41;1m--red light on---\033[0m')
else:
count = 0
event.set() #打开绿灯
time.sleep(1)
count +=1
def car(n):
while 1:
time.sleep(random.randrange(10))
if event.isSet(): #绿灯
print("car [%s] is running.." % n)
else:
print("car [%s] is waiting for the red light.." %n)
if __name__ == '__main__':
event = threading.Event()
Light = threading.Thread(target=light)
Light.start()
for i in range(3):
t = threading.Thread(target=car,args=(i,))
t.start()
来自:http://www.cnblogs.com/yuanchenqi/articles/5733873.html
最新文章
- codeforces 85D D. Sum of Medians 线段树
- 大叔最新课程~EF核心技术剖析
- [问题2014S14] 解答
- Android Fragment 基本介绍
- Java [Leetcode 232]Implement Queue using Stacks
- 2014年百度之星程序设计大赛 - 资格赛 1002 Disk Schedule(双调欧几里得旅行商问题)
- 教你做炫酷的碎片式图片切换 (canvas)
- IIS部署新网站
- Oracle,Sql,procedure 感觉自己写的很棒的一个存储过程
- python第二篇博客,关于数据类型的详细讲解
- 给你的流添加缓冲装置——字节块ByteChunk
- 【Netty】(6) ---源码ServerBootstrap
- python 对Excel表格的读取
- linux中运行.sql文件
- N!分解质因子p的个数_快速求组合数C(n,m)
- MySQL 基础一 安装
- linux下service+命令和直接去执行命令的区别,怎么自己建立一个service启动
- org.hibernate.QueryException: JPA-style positional param was not an integral ordinal; nested exception is java.lang.IllegalArgumentException: org.hibernate.QueryException: JPA-style positional param w
- 【LOJ】#2537. 「PKUWC2018」Minimax
- Flash的swf文件破解