网络编程 - 事件处理

一、事件主要包括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()

猜你喜欢

转载自www.cnblogs.com/wulafuer/p/10240056.html
今日推荐