Python MultiProducer and MultiConsumer
来源:互联网 发布:淘宝会员名怎么改掉 编辑:程序博客网 时间:2024/06/05 11:48
import threadingimport timecondition = threading.Condition() #Condition被称为条件变量,除了提供与Lock类似的acquire和release方法外,还提供了wait和notify方法products = 0class Producer(threading.Thread): '''生产者''' ix = [0] # 生产者实例个数 # 闭包,必须是数组,不能直接 ix = 0 def __init__(self, ix=0): threading.Thread.__init__(self) self.ix[0] += 1 self.setName('生产者' + str(self.ix[0])) def run(self): global condition, products while True: if condition.acquire(): if products < 10: products += 1; print("{}:库存不足(10-)。我努力生产了1件产品,现在产品总数量 {}".format(self.getName(), products)) condition.notify() else: print("{}:库存充足(10+)。让我休息会儿,现在产品总数量 {}".format(self.getName(), products)) condition.wait(); condition.release() #time.sleep(2)class Consumer(threading.Thread): '''消费者''' ix = [0] # 消费者实例个数 # 闭包,必须是数组,不能直接 ix = 0 def __init__(self): threading.Thread.__init__(self) self.ix[0] += 1 self.setName('消费者' + str(self.ix[0])) def run(self): global condition, products while True: if condition.acquire(): if products > 1: products -= 1 print("{}:我消费了1件产品,现在产品数量 {}".format(self.getName(), products)) condition.notify() else: print("{}:只剩下1件产品,我停止消费。现在产品数量 {}".format(self.getName(), products)) condition.wait(); condition.release() time.sleep(5)if __name__ == "__main__": for i in range(5): p = Producer() p.start() for i in range(10): c = Consumer() c.start()
阅读全文
1 0
- Python MultiProducer and MultiConsumer
- python and or and-or
- [Python]private and public
- tcl/tk and python
- python object and class
- Python and Django
- Python and Eclipse
- python Object And Class
- Python and MySQL
- python and Django(二)
- python and Django(一)
- Python and RRD
- python and shell
- F# and Iron Python
- Python if and input
- python and pattern
- Python Dictionary and List
- Python and IRC
- Eclipse中,消除JavaScript报的警告
- android优化的一些经验总结
- 数据库中读取数据批量把时间戳转化为日期时间,用for循环
- Gmail进程信息转储分析工具pdgmail
- RTS,CTS
- Python MultiProducer and MultiConsumer
- 统计每年入职的员工人数
- Java邮箱和手机号的正则表达式验证
- Qt 乱码同时支持多个编码
- 类加载器
- struts2中struts.xml配置文件详解
- npm命令概述
- etcd在同一台虚拟机搭建集群
- Spark术语解释