zoukankan      html  css  js  c++  java
  • Lock版本生产者和消费者模式

    生产者的线程专门用来生产一些数据,存放到一个中间变量中。消费者再从这个中间的变量中取出数据进行消费。但是因为要使用中间变量,中间变量通常是一些全局变量,因此需要使用锁来保证数据完整性。

    import random
    import threading
    
    gMoney = 1000
    gTimes = 0
    gAllTimes = 10
    gLock = threading.Lock()
    
    class Producer(threading.Thread):
        def run(self):
            global gMoney
            global gTimes
            while True:
                money = random.randint(100,1000)  # 随机生成100-1000的数字
                gLock.acquire()
                if gTimes >= gAllTimes:  # 限制生产者只能生产10次
                    gLock.release()   # 满足条件,释放锁
                    break
                gMoney += money
                gTimes += 1           # 生产次数+1
                gLock.release()
                print('{0}生产者生产了{1}元钱,剩余{2}元钱'.format(threading.current_thread(),money,gMoney))
    
    class Consumer(threading.Thread):
        def run(self):
            global gMoney
            while True:
                money = random.randint(100,1000)
                gLock.acquire()
                if gMoney >= money:   # 当剩余钱大于随机生成的钱
                    gMoney -= money
                    print('{0}消费了{1}元钱,剩余{2}元钱'.format(threading.current_thread(), money, gMoney))
                else:
                    if gTimes >= gAllTimes:
                        gLock.release()
                        break
                        print('{0}消费了{1}元钱,剩余{2}元钱,钱不足!'.format(threading.current_thread(),money,gMoney))
    
                gLock.release()
    
    
    def main():
        for i in range(3):
            t2 = Consumer()
            t2.start()
    
        for i in range(4):
            t1 = Producer()
            t1.start()
    
    if __name__ == '__main__':
        main()
  • 相关阅读:
    Java User Thread and Daemon Thread
    BFS 和 DFS
    fail-fast vs fail-safe iterator in Java
    通过先序遍历和中序遍历后的序列还原二叉树
    单例模式总结
    TCP性能陷阱
    数据库事务的四大特性和事务隔离级别
    深入理解Java虚拟机- 学习笔记
    字符串,引用变量与常量池
    深入理解Java虚拟机- 学习笔记
  • 原文地址:https://www.cnblogs.com/suancaipaofan/p/13171769.html
Copyright © 2011-2022 走看看