• 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()
  • 相关阅读:
    洛谷P3959 宝藏(模拟退火乱搞)
    POJA Star not a Tree?(模拟退火)
    HDU 2899Strange fuction(模拟退火)
    洛谷P2062 分队问题(dp)
    主定理与时间复杂度
    android工程混淆和反编译
    查看linux内存、cpu
    Android sqlite数据库存取图片信息
    深入浅出JSONP--解决ajax跨域问题
    分析WordPress主题结构是如何架构的?
  • 原文地址:https://www.cnblogs.com/suancaipaofan/p/13171769.html
Copyright © 2020-2023  润新知