首页 技术 正文
技术 2022年11月15日
0 收藏 873 点赞 4,377 浏览 1278 个字

用 threading.Event() 也可以实现生产者/消费者模式

(自己拍脑袋想出来的,无法知道其正确性,请大神告知为谢!)

import threading
import time
import randomproducts = 20class Producer(threading.Thread):
'''生产者'''
ix = [0] # 生产者实例个数
# 闭包,必须是数组,不能直接 ix = 0 def __init__(self):
super().__init__()
self.ix[0] += 1
self.setName('生产者' + str(self.ix[0])) def run(self):
global producer_signal, products while True:
if products < 10:
if not producer_signal.is_set(): producer_signal.set()
products += 1;
print("{}:库存告急。我努力生产了1件产品,现在产品总数量 {}".format(self.getName(), products))
else:
print("{}:库存充足。我努力生产了0件产品,现在产品总数量 {}".format(self.getName(), products))
if producer_signal.is_set(): producer_signal.wait()
time.sleep(random.randrange(1,4))class Consumer(threading.Thread):
'''消费者'''
ix = [0] # 消费者实例个数
# 闭包,必须是数组,不能直接 ix = 0 def __init__(self):
super().__init__()
self.ix[0] += 1
self.setName('消费者' + str(self.ix[0])) def run(self):
global consumer_signal, products while True:
if products > 1:
if not consumer_signal.is_set(): consumer_signal.set()
products -= 1;
print("{}:我消费了1件产品,现在产品数量 {}".format(self.getName(), products))
else:
print("{}:我消费了0件产品。现在产品数量 {}".format(self.getName(), products))
if consumer_signal.is_set(): consumer_signal.wait()
time.sleep(random.randrange(2,6))if __name__ == "__main__": producer_signal = threading.Event()
consumer_signal = threading.Event() for i in range(2):
p = Producer()
p.start() for i in range(10):
c = Consumer()
c.start()
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,909
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,434
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,249
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,060
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,692
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,730