1. 程式人生 > >event紅綠燈例項

event紅綠燈例項

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()