Python线程event

An event is a simple synchronization object;

the event represents an internal flag, and threads
can wait for the flag to be set, or set or clear the flag themselves.

event = threading.Event()

python线程的事件用于主线程控制其他线程的执行,事件主要提供了三个方法wait、clear、set

# a client thread can wait for the flag to be set
event.wait()

# a server thread can set or reset it
event.set()
event.clear()
If the flag is set, the wait method doesn’t do anything.
If the flag is cleared, wait will block until it becomes set again.
Any number of threads may wait for the same event.

事件处理的机制:全局定义了一个“Flag”,如果“Flag”值为 False,那么当程序执行 event.wait 方法时就会阻塞,如果“Flag”值为True,那么event.wait 方法时便不再阻塞。

  • clear:将“Flag”设置为False
  • set:将“Flag”设置为True

用 threading.Event 实现线程间通信:
使用threading.Event可以使一个线程等待其他线程的通知,我们把这个Event传递到线程对象中,
Event默认内置了一个标志,初始值为False。
一旦该线程通过wait()方法进入等待状态,直到另一个线程调用该Event的set()方法将内置标志设置为True时,
该Event会通知所有等待状态的线程恢复运行。

通过Event来实现两个或多个线程间的交互,下面是一个红绿灯的例子,即起动一个线程做交通指挥灯,生成几个线程做车辆,车辆行驶按红灯停,绿灯行的规则。

import time,threading
event = threading.Event()#生成一个event对象
def light():
    count = 0
    event.set()#先设置绿灯
    while True:
        if count > 5 and count < 10:#改成红灯
          event.clear()#把标志位清空
          print("33[41;1m红灯.....33[0m")
        elif count >10:
          event.set()#变绿灯
          count = 0
        else:
            print("33[42;1m绿灯.....33[0m")
        time.sleep(1)
        count += 1

def car(name):
    while True:
        if event.is_set():#如果设置了标志位,代表绿灯
            print('[%s] running...'%name)
            time.sleep(1)
        else:
            print('%s sees 看到红灯,等着。。。'%name)
            event.wait()#wait方法是等待标志位被设定
            print('33[34;1m[%s] 绿灯了,走。。。33[0m'%name)

l = threading.Thread(target=light,)
l.start()

car1=threading.Thread(target=car,args=('特斯拉',))
car1.start()

 另一种写法:

import threading,time
import random
def light():
    if not event.isSet():#判断标志位是不是被set设定
        event.set() #wait就不阻塞 #绿灯状态
    count = 0
    while True:
        if count < 10:
            print('33[42;1m--green light on---33[0m')
        elif count <13:
            print('33[43;1m--yellow light on---33[0m')
        elif count <20:
            if event.isSet():
                event.clear()
            print('33[41;1m--red light on---33[0m')
        else:
            count = 0
            event.set() #打开绿灯
        time.sleep(1)
        count +=1
def car(n):
    while 1:
        time.sleep(random.randrange(10))
        if  event.isSet(): #绿灯
            print("car [%s] is running.." % n)
        else:
            print("car [%s] is waiting for the red light.." %n)
if __name__ == '__main__':
    event = threading.Event()
    Light = threading.Thread(target=light)
    Light.start()
    for i in range(3):
        t = threading.Thread(target=car,args=(i,))
        t.start()

  

原文地址:https://www.cnblogs.com/tianqizhi/p/9426300.html