python 生产者和消费者模式

"""
生产者和消费者模式:
假设有3个对象,生产者,银行,消费者,银行有1000w的存款,生产者有3个人,一边挣钱一边把钱存入银行,消费者有5人,一边花钱一边
将钱从银行里面取出来
"""
import threading
import random
import time

# 定义银行初始的钱数
chushi_money = 100
chushi_time = 0

# 定义锁
lock = threading.Lock()


# 生产者
class Productor(threading.Thread):
    # 覆写run方法
    def __init__(self, i):
        super().__init__()
        self.i = i

    def run(self):
        global chushi_money
        global chushi_time
        while True:  # 不会停止下去,会一直进行下去,现实中也是这样子的,生产者会一直进行生产下去
            # if chushi_time > 12:
            #     break
            lock.acquire()
            consumer_money = random.randint(100, 300)
            chushi_money += consumer_money
            chushi_time += 1
            print("{}挣了{},银行存款{}".format(self.i, consumer_money,chushi_money))
            lock.release()


# 消费者
class Consumer(threading.Thread):
    def __init__(self, i):
        super().__init__()
        self.i = i

    def run(self):
        global chushi_money
        while True:
            lock.acquire()
            consumer_money = random.randint(200, 300)
            chushi_money -= consumer_money
            if consumer_money > chushi_money:
                print("银行余额不足")
                lock.release()
                break
            print("{}花了{},银行余额为{}".format(self.i, consumer_money,chushi_money))

            lock.release()


if __name__ == '__main__':
    # 定义生产者消费者
    for i in range(1000):
        productor = Productor(i)

        consumer = Consumer(i)
        productor.start()
        consumer.start()
    # # 定义5个消费者
    # for j in range(5):
    #     consumer = Consumer(j)
    #     consumer.start()

    © 2021 GitHub, Inc.
    Terms
    Privacy
    Secu

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生产者-消费者模式是一种常见的并发编程模式,可以有效地解决多线程协作的问题。在爬取网页信息时,我们可以使用生产者-消费者模式来提高效率。 具体实现步骤如下: 1.定义一个生产者类,负责爬取网页信息并将其放入队列中。 2.定义一个消费者类,负责从队列中取出网页信息并进行处理。 3.创建多个生产者消费者线程,并启动它们。 4.使用线程锁来保证队列操作的安全性。 下面是一个简单的示例代码: ```python import threading import queue import requests class Producer(threading.Thread): def __init__(self, url_queue, html_queue): super().__init__() self.url_queue = url_queue self.html_queue = html_queue def run(self): while True: url = self.url_queue.get() html = requests.get(url).text self.html_queue.put(html) self.url_queue.task_done() class Consumer(threading.Thread): def __init__(self, html_queue): super().__init__() self.html_queue = html_queue def run(self): while True: html = self.html_queue.get() # 处理网页信息的代码 self.html_queue.task_done() if __name__ == '__main__': url_queue = queue.Queue() html_queue = queue.Queue() urls = ['http://www.example.com/page{}'.format(i) for i in range(10)] for url in urls: url_queue.put(url) for i in range(5): t = Producer(url_queue, html_queue) t.daemon = True t.start() for i in range(5): t = Consumer(html_queue) t.daemon = True t.start() url_queue.join() html_queue.join() ``` 在这个示例代码中,我们先定义了一个生产者类 `Producer` 和一个消费者类 `Consumer`。生产者负责从 `url_queue` 中取出一个 URL,然后爬取该网页的 HTML 代码,并将其放入 `html_queue` 中。消费者则从 `html_queue` 中取出一个 HTML 代码,然后进行处理。 我们使用了两个队列 `url_queue` 和 `html_queue` 来协调生产者消费者之间的通信。同时,我们创建了 5 个生产者线程和 5 个消费者线程,并启动它们。最后,我们使用 `join()` 方法来等待所有的任务都完成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值