码迷,mamicode.com
首页 > 编程语言 > 详细

python基础 信号量 semaphore evevt 线程queue 生产者消费者模型

时间:2020-03-17 23:50:16      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:put   ==   target   cti   eve   priority   for   python   根据   

线程锁相当于同时只能有一个线程申请锁,有的场景无数据修改互斥要求可以同时让多个线程同时运行,且需要限制并发线程数量时可以使用信号量
 1 import threading, time, queue
 2 
 3 def test(name):
 4     semaphore.acquire() #获取信号量锁
 5     print(my name is %s %name)
 6     time.sleep(1)
 7     semaphore.release() #释放信号量锁
 8 
 9 semaphore = threading.BoundedSemaphore(5) #创建一个信号量同时可以运行3个线程
10 for i in range(20):
11     t = threading.Thread(target=test, args=(i,))
12     t.start()
13 while threading.active_count() == 1:
14     print("all run done")

两个或者多个线程需要交互时,且一个进程需要根据另一线程状态执行对应操作时,可以通过event来设置线程状态达到期望的效果,下面是一个红绿灯的例子

 1 event = threading.Event() #实例化一个event
 2 def light():
 3     while True:
 4         print("红灯亮了,请停车")
 5         time.sleep(20) #开始是红灯20s
 6         event.set() #红灯时间到了,设置标志位
 7         print("绿灯亮了,请通行")
 8         time.sleep(30) #持续30s红灯
 9         event.clear() #清空标志位
10 
11 def car(num):
12     while True:
13         if event.is_set():#检测event被设置则执行
14             print("car %s run"%num)
15             time.sleep(5)
16         else:
17             print("this is red light waiting")
18             event.wait() #此处会卡主,直到状态被设置才会向下执行
19 
20 
21 
22 Light = threading.Thread(target=light,)
23 Light.start()
24 for i in range(10):
25     Car = threading.Thread(target=car, args=(i,))
26     Car.start()

当多个线程需要交互数据可以使用queue来进行数据传递,下面是经典的生产者消费者多线程模型示例,其中包含线程queue的基本使用方法

 1 my_queue = queue.Queue() #实例化一个队列
 2 queue1 = queue.LifoQueue() #后进 先出队列
 3 queue2 = queue.PriorityQueue() #带优先级的队列
 4 def pro():
 5     for i in range(100):
 6         my_queue.put(i) #队列里面放数据
 7 def con():
 8     while my_queue.qsize() > 0: #当队列有数据时候从队列取数据
 9         print("i an a consumer,get num %s"%my_queue.get(timeout=3))
10         time.sleep(2)
11     else:
12         print("my queue is empty")
13 
14 Pro = threading.Thread(target=pro)
15 Pro.start()
16 
17 
18 for j in range(10):
19     Con = threading.Thread(target=con)
20     Con.start()

 

 

 

 

 

 




 

 



python基础 信号量 semaphore evevt 线程queue 生产者消费者模型

标签:put   ==   target   cti   eve   priority   for   python   根据   

原文地址:https://www.cnblogs.com/flags-blog/p/12514561.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!