本文主要是介绍python threading.Event(tcy),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
''''''''' threading.Event 2018/8/23 -------------------------------------------------------------------------------------- 1.class threading.Event实现事件对象的类''' # 是线程之间通信的最简单机制之一,事件是一个简单的线程同步对象 # 事件处理机制: # 全局定义Flag标志,set方法设置flag=true,线程不阻塞; # clear方法重置flag=false(默认值),wait()方法将阻塞 # 用途: # 用threading.Event可以使一个线程等待其他线程的通知,我们把这个Event传递到线程对象中, # Event默认内置了一个标志,初始值为False ---------------------------------------------------------------------------------------方法:is_set() 仅当内部标志为真时返回true。set() 将内部标志设置为true。# 等待它变为真所有线程都被唤醒。wait()一旦标志为真,调用的线程将不会阻塞。clear() 将内部标志重置false。# 随后,线程调用 wait()将阻塞,直到set()被调用以再次将内部标志设置为true。wait(timeout=None) 一直监听flag,如果没有检测到flag就一直处于阻塞状态# 如输入时内部标志为真,则立即返回。# 否则,阻塞直到另一个线程调用 set()将标志设置为true,或者直到发生可选的超时。# 超时参数:一个浮点数,指定操作超时(秒)# 返回值:# 内部标志在等待调用之前或等待开始之后设置为true时,此方法才返回true,# 除非给定超时且操作超时,否则它将始终返回None。 ---------------------------------------------------------------------------------------- 2.实例1: import threading, timedef do(event):print('Start ==> ', time.ctime())event.wait()print('End ==> ', time.ctime())if __name__ == "__main__":event = threading.Event() # 创建一个事件event.clear()t1 = threading.Thread(target=do, args=(event,))t1.start()time.sleep(2)event.set() # 解除阻塞time.sleep(2)print('EndAll==> ', time.ctime())''' Start ==> Fri Sep 21 18:08:43 2018 End ==> Fri Sep 21 18:08:45 2018 EndAll==> Fri Sep 21 18:08:47 2018 ''' ---------------------------------------------------------------------------------------- # 例2.事件在函数及类中的应用。 # event.wait(timeout=1)应用;thread.setDaemon(True)的区别 # 类中使用外部变量Threading.Event;也可将此变量初始化在类中;import threading,timetask_1 = threading.Event() task_2 = threading.Event() task_3 = threading.Event()def run_sub(name):# 等待事件进入阻塞状态print('1.1.task=[{}]satrt...;线程数=[{}];name={};time={}\n'.format(threading.currentThread().name,threading.active_count(),name,time.ctime()))if name=='Tom':task_1.wait()elif name=='John':task_2.wait()else:task_3.wait(timeout=1)# 收到事件进入运行状态print('1.2.task=[{}]run... ;线程数=[{}];name={};time={}\n'.format(threading.currentThread().name, threading.active_count(), name,time.ctime()))time.sleep(4)print('1.3.task=[{}]stop ;线程数=[{}];name={};time={}\n'.format(threading.currentThread().name, threading.active_count(), name,time.ctime()))class MyThread(threading.Thread):def __init__(self, name):threading.Thread.__init__(self)self.task_name = namedef run(self):run_sub(self.task_name) # 重写run方法# # 设置线程组 start=time.time() threads = [] task_names=["Tom","John","Mark"]def test_thread_event():for thread in threads:# thread.setDaemon(True) #True主线程退出子线程退出(无论是否完成)#false主线程完成等待子线程完成后再退出thread.start() # 开启线程time.sleep(2)task_2.set()time.sleep(1)task_1.set()print('......主程序结束......!time=%s\n'%(time.time()-start )) # #****************************************** for i,name in enumerate(task_names):# 创建新线程# 函数测试用以下语句# threads.append(threading.Thread(target=run_sub, args= (name,)))#添加到线程组#类测试用以下语句threads.append(MyThread(name)) # 添加到线程组test_thread_event()#------------------------------------------ ''' C:\python37\python.exe C:/python37/Lib/t4.py 1.1.task=[Thread-1]satrt...;线程数=[2];name=Tom;time=Fri Sep 21 19:42:48 20181.1.task=[Thread-2]satrt...;线程数=[3];name=John;time=Fri Sep 21 19:42:48 20181.1.task=[Thread-3]satrt...;线程数=[4];name=Mark;time=Fri Sep 21 19:42:48 20181.2.task=[Thread-3]run... ;线程数=[4];name=Mark;time=Fri Sep 21 19:42:49 20181.2.task=[Thread-2]run... ;线程数=[4];name=John;time=Fri Sep 21 19:42:50 2018......主程序结束......!time=3.002171754837036 1.2.task=[Thread-1]run... ;线程数=[4];name=Tom;time=Fri Sep 21 19:42:51 20181.3.task=[Thread-3]stop ;线程数=[4];name=Mark;time=Fri Sep 21 19:42:53 20181.3.task=[Thread-2]stop ;线程数=[3];name=John;time=Fri Sep 21 19:42:54 20181.3.task=[Thread-1]stop ;线程数=[2];name=Tom;time=Fri Sep 21 19:42:55 2018Process finished with exit code 0''' ---------------------------------------------------------------------------------------- # 例3.事件在两个类之间通过list,event对象传递参数; # 可以在线程内部及外部控制event对象 # import time from threading import Thread, Event from collections import deque # n=100 items = deque() task1 = Event() # class eat_a_meal(Thread):def __init__(self, items, task1,n):Thread.__init__(self)self.items = itemsself.task1 = task1self.n=n#def run(self):while True:self.task1.wait()if self.items:food = self.items.popleft()if food == 'stop_cook':breakself.n -= 1print("2.2.正在吃1pcs 【%s】...;ThreadName=【%s】;n = 【%d】\n"% (food, self.name, self.n))time.sleep(1)else:if food!='热狗':print("2.1.饭未做好,等待...\n")else:print("3.程序退出...")self.task1.clear()class cook_a_meal(Thread):def __init__(self, items, task1,n):Thread.__init__(self)self.items = itemsself.task1 = task1self.n=nself.cook_category=['包子','馒头','油条','豆浆','鸡蛋','热狗','stop_cook']def run(self):for food in self.cook_category:time.sleep(2) #做饭时间self.n+=2self.items.append(food)self.task1.set() #解除eat_a_meal 类的阻塞if food!='stop_cook':print("1.制作完成1pcs 【%s】出售中...;ThreadName=【%s】;n = 【%d】\n"% (food, self.name, self.n)) # ****************************************** if __name__ == "__main__":producer = cook_a_meal(items, task1,n)consumer = eat_a_meal(items, task1,n)producer.start()consumer.start()producer.join()consumer.join()''' # 1.制作完成1pcs 【包子】出售中...;ThreadName=【Thread-1】;n = 【102】 # 2.2.正在吃1pcs 【包子】...;ThreadName=【Thread-2】;n = 【99】 # 2.1.饭未做好,等待... # 1.制作完成1pcs 【馒头】出售中...;ThreadName=【Thread-1】;n = 【104】 # 2.2.正在吃1pcs 【馒头】...;ThreadName=【Thread-2】;n = 【98】 # 2.1.饭未做好,等待... # 1.制作完成1pcs 【油条】出售中...;ThreadName=【Thread-1】;n = 【106】 # 2.2.正在吃1pcs 【油条】...;ThreadName=【Thread-2】;n = 【97】 # 2.1.饭未做好,等待... # 1.制作完成1pcs 【豆浆】出售中...;ThreadName=【Thread-1】;n = 【108】 # 2.2.正在吃1pcs 【豆浆】...;ThreadName=【Thread-2】;n = 【96】 # 2.1.饭未做好,等待... # 1.制作完成1pcs 【鸡蛋】出售中...;ThreadName=【Thread-1】;n = 【110】 # 2.2.正在吃1pcs 【鸡蛋】...;ThreadName=【Thread-2】;n = 【95】 # 2.1.饭未做好,等待... # 1.制作完成1pcs 【热狗】出售中...;ThreadName=【Thread-1】;n = 【112】 # 2.2.正在吃1pcs 【热狗】...;ThreadName=【Thread-2】;n = 【94】 # 3.程序退出... ''' ---------------------------------------------------------------------------------------------- # 实例4:利用Event类模拟红绿灯 import threading, timeevent1 = threading.Event() event2 = threading.Event()def lighter():while True:event1.set() # 东西绿灯event2.clear() # 南北红灯print("\33[42;1m [1.east_wast :GreenLight ...]\033[0m")print("\33[41;1m [2.north_south:RedLight ...]\033[0m")time.sleep(2)event2.set() # 东西红灯event1.clear() # 南北绿灯print('------------------------------------')print("\33[42;1m [2.north_south:GreenLight ...]\033[0m")print("\33[41;1m [1.east_wast :RedLight ...]\033[0m")time.sleep(2)# ------------------------------------------------------- def car(name):b1 = 0;b2 = 0;while True:if event1.is_set() and (not b1): # 判断是否设置了标志位b1 = 1;b2 = 0;print("[1.%s east_wast running ]" % name)print("[2.%s north_south waiting]" % name)elif not (event1.is_set() and b2):b2 = 1;b1 = 0;print("[2.%s north_south running]" % name)print("[1.%s east_wast waiting ]" % name)event1.wait()event2.wait()# ------------------------------------------------------- light = threading.Thread(target=lighter, ) light.start() car = threading.Thread(target=car, args=("JinBei car:",)) car.start()''' [1.east_wast :GreenLight ...] [2.north_south:RedLight ...] [1.JinBei car: east_wast running ] [2.JinBei car: north_south waiting] ------------------------------------ [2.JinBei car: north_south running] [1.JinBei car: east_wast waiting ] [2.north_south:GreenLight ...] [1.east_wast :RedLight ...]''' ------------------------------------------------------------------------------
这篇关于python threading.Event(tcy)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!