温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

event红绿灯实例

发布时间:2020-07-23 19:33:39 来源:网络 阅读:211 作者:leiwenbin627 栏目:编程语言

import threading,time

event=threading.Event() #生成一个event对象

def lighter():
    count=0
    event.set()#开始设置标志位 绿灯 设置了标志位程序就通行
    while True:
        if count>5 and count<10:#改成红灯 6~9为红灯
            event.clear() #把标志位清了
            print("\033[41;1mred light is on ...\033[0m")
        elif count>10:
            event.set()#变绿灯 设置标志位
            count = 0 #count清零 重新开始
        else:
            print("\033[42;1mgreen light is on ...\033[0m") #0~5位绿灯
        time.sleep(1) #每隔一秒记一次
        count +=1

def car(name):
    while True:
        if event.is_set(): #is_set 判断是否设置标志位 设置了标志位为绿灯 通行
            print("[%s] running..."%name)
            time.sleep(1)
        else:
            print("[%s] sees red light,waiting..."%name)
            event.wait() #wait卡住,等待标志位被设定 等到标志位设定之后程序再往下走
            print("\033[34;1m[%s] green light is on,start going...\033[34;0m"%name)


light=threading.Thread(target=lighter,)
light.start()

car1=threading.Thread(target=car,args=("Honda",))
car1.start()

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI