条件同步和条件变量同步差不多意思,只是少了锁功能,因为条件同步设计于不访问共享资源的条件环境,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

最新文章

  1. codeforces 85D D. Sum of Medians 线段树
  2. 大叔最新课程~EF核心技术剖析
  3. [问题2014S14] 解答
  4. Android Fragment 基本介绍
  5. Java [Leetcode 232]Implement Queue using Stacks
  6. 2014年百度之星程序设计大赛 - 资格赛 1002 Disk Schedule(双调欧几里得旅行商问题)
  7. 教你做炫酷的碎片式图片切换 (canvas)
  8. IIS部署新网站
  9. Oracle,Sql,procedure 感觉自己写的很棒的一个存储过程
  10. python第二篇博客,关于数据类型的详细讲解
  11. 给你的流添加缓冲装置——字节块ByteChunk
  12. 【Netty】(6) ---源码ServerBootstrap
  13. python 对Excel表格的读取
  14. linux中运行.sql文件
  15. N!分解质因子p的个数_快速求组合数C(n,m)
  16. MySQL 基础一 安装
  17. linux下service+命令和直接去执行命令的区别,怎么自己建立一个service启动
  18. 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
  19. 【LOJ】#2537. 「PKUWC2018」Minimax
  20. Flash的swf文件破解

热门文章

  1. javascript进行base64加密,解密
  2. js设置下拉框选中后change事件无效解决
  3. java——程序的导出与导入
  4. 四、jdbctemplate使用
  5. MongoDB 学习(二)可视化界面
  6. MyBatis入门篇
  7. JavaScript对HTML字符转义与反转义(转码和解码)
  8. xml文件读取到数据库
  9. 使用SlidingPaneLayout 实现仿微信的滑动返回
  10. 任务九:使用HTML/CSS实现一个复杂页面