python(红绿灯、汽车 time、threading模块)

# Author: Sooele

import time  #时间模块
import threading  #线程模块

event = threading.Event()


def lighter():
    count = 0
    event.set()  #先设置绿灯
    while True:
        if count >5 and count < 10: #改成红灯
            event.clear() #把标志位清了
            print("\033[41;1mred light is on....\033[0m")
        elif count >10:
            event.set() #变绿灯
            count = 0
        else:
            print("\033[42;1mgreen light is on....\033[0m")
        time.sleep(1)
        count +=1

def car(name):
    while True:
        if event.is_set(): #代表绿灯
            print("[%s] running ...."% name)  #运行
            time.sleep(1)
        else:
            print("[%s] sees red light,waiting ...."% name)
            event.wait()   #等待
            print("\033[34:1m[%s]green light is on ,start gooing..\033[1m" % name)



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

car1 = threading.Thread(target=car,args=("玛莎拉蒂",))
car1.start()

event.wait()

# a server thread can set or reset it
event.set()
event.clear()
If the flag is set, the wait method doesn’t do anything.
标志位设定了,代表绿灯,直接通行
If the flag is cleared, wait will block until it becomes set again.
标志位被清空,代表红灯,wait等待变绿灯
Any number of threads may wait for the same event.

 

发表评论