event 实现两个程序的交互

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

















 

转载于:https://www.cnblogs.com/my-love-is-python/p/9134813.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值