Python 编程 多线程 中的 event

1 篇文章 0 订阅
1 篇文章 0 订阅

转载自https://blog.csdn.net/mouday/article/details/79146183

红绿灯实例,event事件

import time, threading

event = threading.Event()

# 交通灯
def lighter():
    count = 0
    while True:
        if count < 5:  # 绿灯
            event.set()  #设置标志位
            print("\033[42;1m 绿灯亮\033[0m")
        elif count > 10:
            count =0  # 清零重新计数
        else:  # 红灯
            event.clear()  # 清空标志位
            print("\033[41;1m 红灯亮\033[0m")

        time.sleep(1)
        count += 1

# 车辆
def car(name):
    while True:
        if event.is_set():  # 绿灯亮
            print("[%s]绿灯行..." % name)
            time.sleep(1)
        else:
            print("[%s]红灯停!!!" % name)
            event.wait()  # 等待标志位设定
            print("\033[34;1m绿灯出发\033[0m")

# 启动交通灯
t_lighter = threading.Thread(target=lighter)
t_lighter.start()

# 放入车辆
t_car1 = threading.Thread(target=car, args=("奥迪车",))
t_car2 = threading.Thread(target=car, args=("大众车",))
t_car1.start()
t_car2.start()

# 备注,\033在pycharm中有效果
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值