Python线程的事件用于主线程控制其他线程的执行,事件主要提供了三个方法wait、clear、set,通过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 = threading.Event()#客户端线程可以等待标志被设置
  • event.wait() #服务器线程可以设置或重置它
  • event.set() #如果该标志已设置,则等待方法不会执行任何操作。
  • event.clear()#如果标志被清除,等待将被阻塞,直到它再次被设置。

任何数量的线程都可能等待相同的事件。

举例:

下面是一个红绿灯的例子,即起动一个线程做交通指挥灯,生成几个线程做车辆,车辆行驶按红灯停,绿灯行的规则。



import threading
import time,random

event = threading.Event()

def lighter():
    count = 0
    event.set() #先设置绿灯
    while True:
        if count > 5 and count < 10 : #改成红灯
            event.clear() #把标注位清空
            print("\033[41;1m red light is on...\033[0m")
        elif count > 10:
            event.set() #变绿灯
            count = 0
        else:
            print("\033[42;1m  green  is on...\033[0m")
        time.sleep(1)
        count += 1

def car(name):
    while True:
        time.sleep(random.randrange(10))
        if event.is_set(): #设置标志位代表绿灯
            print("[%s] running ..." % name )
        else:
            print("[%s] sees red light , waiting ..." % name )
            event.wait()
            print ("\033[34;1m[%s] green light is on ,start going ...\033[0m" % name)

light = threading.Thread(target=lighter,)
light.start()
for i in range(3):#假设有4台机器,编号从0 - 3 ,随机抽取
    car1 = threading.Thread(target=car,args=(i,))
    car1.start()
输出:
  green  is on...
[0] running ...
  green  is on...
  green  is on...
[0] running ...
  green  is on...
  green  is on...
  green  is on...
[2] running ...
 red light is on...
[1] sees red light , waiting ...
 red light is on...
 red light is on...
[0] sees red light , waiting ...
 red light is on...
  green  is on...
[1] green light is on ,start going ...
[0] green light is on ,start going ...
  green  is on...



参考大王的例子



import threading,time
import random
def light():
    if not event.isSet():
        event.set() #设置标志位,wait就不阻塞,为绿灯状态
    count = 0
    while True:
        if count < 5:
            print('\033[42;1m--green light on---\033[0m')
        elif count < 8:
            print('\033[43;1m--yellow light on---\033[0m')
        elif count <15:
            if event.isSet():
               event.clear()
            print('\033[41;1m--red light on---\033[0m')
        else:
            count = 0
            event.set() #count归零,重新设置标志位,打开绿灯
        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(1,5):
        t = threading.Thread(target=car,args=(i,))
        t.start()



 


广告,插入Timer函数讲解


Timer函数讲解


类表示只有经过一段时间才应该运行的动作,定时器和线程一样,通过调用它们的start()方法来启动。通过调用cancel()方法可以停止计时器(在其动作开始之前)。计时器在执行其动作之前等待的时间间隔可能与用户指定的时间间隔不完全相同。
举例:



import threading
def hello():
    print("hello world")

t = threading.Timer(30,hello) #30为等待的时间,按秒计算
t.start()
输出:
hello world