线程锁相当于同时只能有一个线程申请锁,有的场景无数据修改互斥要求可以同时让多个线程同时运行,且需要限制并发线程数量时可以使用信号量
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()