多线程模拟红绿灯
import threadingimport time
event=threading.Event()#声明事件
def liger():
count=0
event.set() #设置标志位,默认为绿灯
while True:
if count in range(6,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.set(): #判定是否标志,绿灯
print("[%s] running..." % name)
time.sleep(1)
else:
print("[%s] sees red light , waiting..." % name)
event.wait()# 标志位没设,就卡住,设置了就执行(等待标志位被设定)
print("\033 green light is on ,start going...\033[0m" % name)
if __name__ == '__main__':
light=threading.Thread(target=liger)
car=threading.Thread(target=car,args=("小车",))
light.start()
car.start()
页:
[1]