博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
多线程Lock版生产者和消费者模式
阅读量:4677 次
发布时间:2019-06-09

本文共 1368 字,大约阅读时间需要 4 分钟。

#encoding: utf-8 import threading import random import time gMoney = 1000 gLock = threading.Lock() gTotalTimes = 10 gTimes = 0 class Producer(threading.Thread):     def run(self):         global gMoney         global gTimes         while True:             money = random.randint(100,1000)             gLock.acquire()             if gTimes > 10:                 gLock.release()                 break             gMoney += money             print('%s生产了%d元钱,剩余%d元钱'%(threading.current_thread(),money,gMoney))             gTimes += 1             gLock.release()             time.sleep(0.5) class Consumer(threading.Thread):     def run(self):         global gMoney         while True:             money = random.randint(100,1000)             gLock.acquire()             if gMoney >= money:                 gMoney -=money                 print('%s消费了%d元钱,剩余%d元钱'%(threading.current_thread(),money,gMoney))             else:                 if gTimes >= gTotalTimes:                     gLock.release()                     break                 print('不足')             gLock.release()             time.sleep(0.5) def main():     for x in range(3):         t = Consumer(name='消费者线程%d'%x)         t.start()     for x in range(5):         t = Producer(name='生产者线程%d'%x)         t.start() if __name__ == '__main__':     main()

转载于:https://www.cnblogs.com/cyz123/p/10639159.html

你可能感兴趣的文章
【堆】这是要搞事情啊——取出
查看>>
观察者模式与发布/订阅模式的区别
查看>>
洛谷P2144 bzoj1002 [FJOI2007]轮状病毒 (高精度板子)
查看>>
开发基于vue前端框架下的系统的UI自动化,记录总结踩的坑
查看>>
dede:channel的type改为son,currentstyle当前样式就不起作用
查看>>
Target Operator ID has No Access to Upgrade
查看>>
js 浅谈 toString和toLocaleString的区别
查看>>
Vue的生命周期
查看>>
3、学大数据笔记-hadoop2的配置
查看>>
【蜕变】搭建史上真正没有注水的VueUI库Nature-UI,包含18个复杂组件
查看>>
[译] Web 流式文字排版的现状
查看>>
Spring Boot 拦截器
查看>>
Spring Boot 集成 Thymeleaf 布局遇坑
查看>>
Bootstrap TreeView 标签name=parentNode引起页面卡死(以及nodeId)
查看>>
集合的复杂排序
查看>>
2019.9.7感想
查看>>
Lint检查选项
查看>>
百度群组链接分享 - 铁人圈子
查看>>
ASCII码
查看>>
2019年JD PHP工程师面试题
查看>>