13-多线程爬虫-Lock版的生产者和消费者模式

Lock版的生产者和消费者模式:
生产者和消费者模式是多线程开发中经常见到的一种模式。
生产者的线程专门用来生产一些数据,然后存放到一个中间变量中。消费者再从这个中间的变量中取出数据进行消费。
通过生产者和消费者模式,可以让代码达到高内聚低耦合的目标,程序分工更加明确,线程更加方便管理

# 生产者和消费者模式(生产者用来挣钱,消费者用来花钱)

import threading
import random

# 全局变量
gMoney = 0
# 生成一个锁对象
gLock = threading.Lock()
# 生产者生产的次数
gTimes = 0

class Producer(threading.Thread):
    # 告诉别人,这个函数只返回None
    def run(self) -> None:
        # 当前线程的对象
        the_thread = threading.current_thread()
        
        global gTimes,gMoney
        
        while True:
            # 加锁
            gLock.acquire()
            
            if gTimes >= 10:
                gLock.release()
                break

            money = random.randint(0,100)
            gMoney += money
            gTimes += 1
            print("当前线程:{0}\t赚了{1}元,存款为{2}元".format(the_thread.name,money,gMoney))

            # 释放锁
            gLock.release()
    
class Consumer(threading.Thread):
    def run(self) -> None:
        # 当前线程的对象
        the_thread = threading.current_thread()
        
        global gMoney
        
        while True:
            # 加锁
            gLock.acquire()

            money = random.randint(0,100)
            if gMoney >= money:
                gMoney -= money
                print("当前线程:{0}\t花了{1}元,存款为{2}元".format(the_thread.name,money,gMoney))
            else:
                print("当前线程:{0}\t余额不足,预支付{1}元,但余额只有{2}元".format(the_thread.name,money,gMoney))
                if gTimes >= 10:
                    gLock.release()
                    break

            # 释放锁
            gLock.release()
       
def main():
    # 创建五个生产者进程
    for x in range(5):
        thread_producer = Producer(name="生产者{}".format(x))
        thread_producer.start()
        
    # 创建五个消费者进程
    for y in range(5):
        thread_consumer = Consumer(name="消费者{}".format(y))
        thread_consumer.start()
        
if __name__ == "__main__":
    main()

执行结果

 

posted @ 2021-04-26 20:02  马铃薯1  阅读(61)  评论(0编辑  收藏  举报