python生产和消费模型_Python semaphore evevt生产者消费者模型原理解析

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

import threading, time, queue

def test(name):

semaphore.acquire() #获取信号量锁

print('my name is %s' %name)

time.sleep(1)

semaphore.release() #释放信号量锁

semaphore = threading.BoundedSemaphore(5) #创建一个信号量同时可以运行3个线程

for i in range(20):

t = threading.Thread(target=test, args=(i,))

t.start()

while threading.active_count() == 1:

print("all run done")

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

event = threading.Event() #实例化一个event

def light():

while True:

print("红灯亮了,请停车")

time.sleep(20) #开始是红灯20s

event.set() #红灯时间到了,设置标志位

print("绿灯亮了,请通行")

time.sleep(30) #持续30s红灯

event.clear() #清空标志位

def car(num):

while True:

if event.is_set():#检测event被设置则执行

print("car %s run"%num)

time.sleep(5)

else:

print("this is red light waiting")

event.wait() #此处会卡主,直到状态被设置才会向下执行

Light = threading.Thread(target=light,)

Light.start()

for i in range(10):

Car = threading.Thread(target=car, args=(i,))

Car.start()

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

my_queue = queue.Queue() #实例化一个队列

queue1 = queue.LifoQueue() #后进 先出队列

queue2 = queue.PriorityQueue() #带优先级的队列

def pro():

for i in range(100):

my_queue.put(i) #队列里面放数据

def con():

while my_queue.qsize() > 0: #当队列有数据时候从队列取数据

print("i an a consumer,get num %s"%my_queue.get(timeout=3))

time.sleep(2)

else:

print("my queue is empty")

Pro = threading.Thread(target=pro)

Pro.start()

for j in range(10):

Con = threading.Thread(target=con)

Con.start()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持python博客。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值