标签:tar nbsp red comm 红绿灯 += thread state The
event.wait() 等待一定时间,或者当遇到event.set() 时,继续执行
event.clear() 清除信号
event.set() 设置信号
event.isset() 判断信号
例一: 红绿灯
#event 实现两个线程之间的交互
import time, threading
def lighter():
if not event.is_set():
event.set()
count = 0
while True:
if count<10:
print(‘the green light is run %s‘%count)
elif count<15:
print(‘the yellow light is run %s‘%count)
elif count<20:
print(‘the red light is run %s‘%count)
event.clear()
else:
count = 0
event.set()
time.sleep(1)
count += 1
def cars(n):
while True:
if event.is_set():
print(‘%s is running‘%n)
else:
print(‘%s is stoping‘%n)
time.sleep(1)
event = threading.Event()
light = threading.Thread(target=lighter, args=())
light.start()
car = threading.Thread(target=cars, args=(‘tesl‘, ))
car.start()
例二 开关门
import threading, time, random
def door():
door_count_number = 0
while True:
if door_state.is_set():
print(‘the door is open‘)
door_count_number += 1
else:
print(‘the door has been closed‘)
door_count_number = 0
door_state.wait()
if door_count_number > 3:
door_state.clear()
time.sleep(0.5)
def staff(n):
print(‘%s is comming‘%n)
while True:
if door_state.is_set():
print(‘%s is pass‘%n)
break
else :
door_state.set()
print(‘staff[%s]sees door got closed, swipped the card‘)
time.sleep(0.5)
door_state = threading.Event()
Door = threading.Thread(target=door)
Door.start()
for i in range(5):
p = threading.Thread(target=staff, args=(i, ))
time.sleep(random.randrange(3))
p.start()
标签:tar nbsp red comm 红绿灯 += thread state The
原文地址:https://www.cnblogs.com/my-love-is-python/p/9134813.html