网络编程 - 事件处理

一、事件主要包括3种:

1、event.set() #设置标志位;

2、event.clear() #清除标志位;

3、event.wait() #未设置标志位时,等待;

4、以下例子,实现红绿灯及车的线程关系(当红灯时,车等待,当绿灯时,车通行)

     通过对红绿灯线程设置事件的标志位,当设置标志位时,代表车辆通行。当标志位清除时,代表红灯,代表车辆等待。当再次设置标志位时,车辆等待清除,视为绿灯)。

 

import threading,time
event = threading.Event()



def lighter():
event.set()
count = 1
while True:
if count<=6 and count>3:#清除标志位,代表红灯;
event.clear()
print("\033[41;1mred light is on...\033[0m")
elif count>6 :#设置标志位,代表绿灯;
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] is running..." % name)
time.sleep(1)
else:
print ("[%s] sees red light...waiting..." % name)
event.wait()
print ("green light is on ,going....")

light = threading.Thread(target=lighter)
light.start()
car = threading.Thread(target=car,args=("tesla",))
car.start()

转载于:https://www.cnblogs.com/wulafuer/p/10240056.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值