python爬虫-24-python多线程详解(3)生产者和消费者模式

图片

1、lock版本生产者和消费者

生产者和消费者是多线程开发中经常遇到的一个模式。生产者专门用来生产一些数据,然后存放到一个变量中。消费者再从这个变量中取出数据进行消费。因为中间经常是一些全局变量,故而经常使用来保证数据的完整性。

我们通过一个money的例子来认识下。

首先,我们假设有一个家庭,初始资金有1000元,有3个人在挣钱,两个人在花钱,挣的钱我们就存到银行,消费的也从银行消费。就这样一个简单的例子来认识下生产者和消费者吧。(我们假设时间短一点儿哈,假设能挣钱5次吧,这样子比较简单直观。)

我们首先简简单单先来写个小框框,如下:

# Lock 生产者和消费者

import threading


# 生产者
class producter(threading.Thread):
    def run(self):
        pass


# 消费者
class consumer(threading.Thread):
    def run(self):
        pass


def main():
    for i in range(3):
        producter(name='生产者-{}'.format(i)).start()

    for i in range(2):
        consumer(name='消费者-{}'.format(i)).start()


if __name__ == '__main__':
    main()

然后我们稍微完善一下子,然后代码就变成了下面的样子:

import threading
import random
import time

Total_money = 1000
A_lock = threading.Lock()
Get_money = 5
Count = 0


# 生产者
class producter(threading.Thread):
    def run(self):
        global Total_money
        global Get_money
        global Count
        print("我是{},我来挣钱了。".format(threading.current_thread()))
        while True:
            A_lock.acquire()
            if Count < Get_money:
                product = random.randint(5000, 10000)
                Total_money += product
                print('{}挣了{}钱,银行总金额为{}元。'.format(threading.current_thread(), product, Total_money))
                Count += 1
                time.sleep(1)
                A_lock.release()
            else:
                A_lock.release()
                break


# 消费者
class consumer(threading.Thread):
    def run(self):
        global Total_money
        global Get_money
        global Count
        print("我是{},我来消费了。".format(threading.current_thread()))
        while True:
            consume = random.randint(2000, 10000)
            A_lock.acquire()
            if Total_money >= consume:
                Total_money -= consume
                print('{}花了{}元,银行剩余{}元。'.format(threading.current_thread(), consume, Total_money))
                time.sleep(1)
                A_lock.release()
            else:
                if Count <= Get_money:
                    print('{}想花{}元,银行剩余{}元,不足消费,且生产者不生产钱咯,破产咯!!!'.format(threading.current_thread(), consume, Total_money))
                    A_lock.release()
                    break
                print('{}想花{}元,银行剩余{}元,不足消费,没办法花钱咯!!!'.format(threading.current_thread(), consume, Total_money))
                A_lock.release()


def main():
    for i in range(3):
        producter(name='生产者-{}'.format(i)).start()

    for i in range(2):
        consumer(name='消费者-{}'.format(i)).start()


if __name__ == '__main__':
    main()

运行结果如下:

我是<producter(生产者-0, started 6468)>,我来挣钱了。
<producter(生产者-0, started 6468)>挣了5954钱,银行总金额为6954元。
我是<producter(生产者-1, started 23940)>,我来挣钱了。
我是<producter(生产者-2, started 13540)>,我来挣钱了。
我是<consumer(消费者-0, started 8200)>,我来消费了。
我是<consumer(消费者-1, started 10524)>,我来消费了。
<producter(生产者-0, started 6468)>挣了5931钱,银行总金额为12885元。
<producter(生产者-0, started 6468)>挣了5609钱,银行总金额为18494元。
<producter(生产者-0, started 6468)>挣了6990钱,银行总金额为25484元。
<consumer(消费者-1, started 10524)>花了3848元,银行剩余21636元。
<producter(生产者-1, started 23940)>挣了6851钱,银行总金额为28487元。
<consumer(消费者-1, started 10524)>花了9547元,银行剩余18940元。
<consumer(消费者-0, started 8200)>花了4626元,银行剩余14314元。
<consumer(消费者-1, started 10524)>花了7766元,银行剩余6548元。
<consumer(消费者-0, started 8200)>想花6608元,银行剩余6548元,不足消费,且生产者不生产钱咯,破产咯!!!
<consumer(消费者-1, started 10524)>花了2812元,银行剩余3736元。
<consumer(消费者-1, started 10524)>花了2771元,银行剩余965元。
<consumer(消费者-1, started 10524)>想花8104元,银行剩余965元,不足消费,且生产者不生产钱咯,破产咯!!!

2、Condition版本生产者与消费者模式

当我们使用lock版本的生产者和消费者的时候,会发现一个问题,就是说当你消费者消费的金额不足的情况下,但是生产者生产数量还小于我们设定的 5次的时候,这个时候呢,他不满足我们设定的break方法,那么就会一直处于一个长时间死循环的一种情况。但是加锁解锁又是要消耗CPU等性能的,所以在这个情况下,我们的Condition就应运而生了;

ConditionLock相比有什么区别呢,就是Condition添加了一个**wait机制,那么Conditionwait机制是什么呢?他就是用来当不满足指定条件、且也不满足该线程停止的条件时,让该线程处于一个等待状态**,不让它运行了,一直等到有“人”通知他的时候,他将再次运行起来。

回归到咱们这个例子的情况下就是,在生产者生产金钱的次数,不足5次的时候,消费者消费的金额已经将银行里面的钱花完了,那么当他再次消费的时候,就让他处于wait状态,让他等着,不是说不让他花钱了,是让他等着生产者生产金钱之后通知他,他再继续消费,在某些情况下将大大减少性能的浪费

方法:

import threading
A_Condition = threading.Condition()  # 生成Condition锁
A_Condition.acquire()  # 上锁
A_Condition.release()  # 解锁
A_Condition.wait()  # 让该线程等待
A_Condition.notify()  # 解锁指定等待的线程,默认是第一个线程
A_Condition.notifyAll()  # 解锁所有处于等待状态的线程

注意:

notifynotifyAll是不会释放锁的,所以他的运行应该在release之前。

所以当我们上面的例子,使用了Condition方法之后的代码应该是这样子的:

剩余内容请转至VX公众号 “运维家” ,回复 “185” 查看。

------ “运维家” ,回复 “185” ------
------ “运维家” ,回复 “185” ------
------ “运维家” ,回复 “185” ------

系统运维工程师,运维工程师技能要求,成都运维工程师驻场开发收费标准,t3网络运维工程师,运维工程师社会需求,运维工程师修炼手册;
oppo高级运维工程师社招,运维工程师员招聘要求,中级运维工程师技术水平,大数据运维工程师月薪多少,运维工程师的个人发展计划,应届生面试运维工程师穿着;
系统运维运维工程师,中国移动网络运维工程师笔试,徐州市苏宠集团运维工程师待遇,云南运维工程师培训班;
监控系统运维工程师,高铁运维工程师是正式工 吗,郑卅软件运维工程师招聘,运维助理工程师好不好。

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
生产者-消费者模式是一种经典的多线程模式,其中一个或多个生产者生成数据并将其放入缓冲区,而一个或多个消费者从缓冲区中读取数据并进行处理。下面是一个使用Python实现的生产者-消费者模式的简单例子: ```python import threading import queue import time # 定义一个缓冲区 buffer = queue.Queue(maxsize=10) # 生产者线程函数 def producer(): while True: # 生产一个数据 data = time.time() # 将数据放入缓冲区 buffer.put(data) print("Producer: produced item %s" % data) # 等待一段时间 time.sleep(1) # 消费者线程函数 def consumer(): while True: # 从缓冲区中取出一个数据 data = buffer.get() print("Consumer: consumed item %s" % data) # 处理数据 # ... # 通知缓冲区数据已经被处理 buffer.task_done() # 创建生产者消费者线程 producer_thread = threading.Thread(target=producer) consumer_thread = threading.Thread(target=consumer) # 启动线程 producer_thread.start() consumer_thread.start() # 等待所有线程结束 producer_thread.join() consumer_thread.join() ``` 在这个例子中,我们使用了Python内置的`queue`模块来实现缓冲区。首先,我们创建了一个`Queue`对象作为缓冲区,并设置了最大容量为10。然后,我们定义了生产者消费者线程函数,分别用于生成数据和处理数据。在生产者线程中,我们使用`put`方法将数据放入缓冲区。在消费者线程中,我们使用`get`方法从缓冲区中取出数据,并使用`task_done`方法通知缓冲区数据已经被处理。 最后,我们创建生产者消费者线程,并启动它们。在主线程中,我们使用`join`方法等待所有线程结束。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

运维家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值