生产者消费者模型

文章目录

  • 简介
  • 生产者消费者示例1
  • 生产者消费者示例2

简介

在线程中,生产者就是生产数据的线程,消费者就是消费数据的线程。在多线程开发中,由于生产者和消费者处理速度的差异,就会产生等待,造成时间浪费。

生产者消费者模式通过一个容器解决了生产者和消费者的强耦合问题。生产者和消费者彼此之间不直接通讯,而是通过阻塞队列通讯。生产者生产完之后直接丢给阻塞队列,而不必等待消费者;消费者反之同理。阻塞队列相当于一个缓冲区,平衡了生产者和消费者的处理能力。

生产者消费者模型_第1张图片


生产者消费者示例1

'''
@file: producer_consumer_1.py
@author: zyh
@time: 2023/5/10 10:00

生产者消费者模型实例1。
'''
import time
import random
import queue
import threading

q = queue.Queue()   # FIFO

def producer(name):
    count = 1
    while count < 5:
        print('cooking...')
        time.sleep(1)
        q.put(count)
        print('\033[1;31mproducer {} has cooked {} hamburgers.\033[0m'.format(name, count))
        count += 1
        print('DONE!')
        
def consumer(name):
    count = 0
    while count < 5:
        time.sleep(1)
        if not q.empty():
            data = q.get()
            print('\033[32;1mConsumer {} has eaten {} hamburger...\033[0m'.format(name, data))
        else:
            print('No Humburger Anymore')
        count += 1
        
p1 = threading.Thread(target=producer, args='A')

c1 = threading.Thread(target=consumer, args='B')
c2 = threading.Thread(target=consumer, args='C')

p1.start()
c1.start()
c2.start()

Python如何控制终端的字符颜色?
书写格式:print('\033[文字效果;前景色;背景色m文字内容\033[0m')
【注】三个参数为可选参数,至少写一个,参数书写没有顺序
生产者消费者模型_第2张图片

参数值说明

e.g. print('\033[32;1mConsumer {} has eaten {} hamburger...\033[0m'.format(name, data))


更多内容参考Python终端打印彩色字符


生产者消费者示例2

在一些场景下,需要生产者生产完产品后通知消费者,消费者得到通知再做自己的事。

'''
@file: producer_consumer_2.py
@author: zyh
@time: 2023/5/10 11:10

生产者消费者模型实例2。
'''
import time
import random
import threading
import queue

q = queue.Queue()

def producer(name):
    count = 0
    while count < 10:
        print('cooking...')
        time.sleep(1)
        q.put(count)
        print('\033[1;31mProducer {} has cooked No.{} hamburgers.\033[0m'.format(name, count))
        count += 1
        q.task_done()
        print('DONE!')
        

def consumer(name):
    count = 1
    while count < 10:
        q.join()
        data = q.get()
        print('\033[1;32mConsumer {} has eaten No.{} hamburger.\033[0m'.format(name, data))
        count += 1

p = threading.Thread(target=producer, args='A')

c1 = threading.Thread(target=consumer, args='B')
c2 = threading.Thread(target=consumer, args='C')

p.start()
c1.start()
c2.start()

输出:

cooking...
Producer A has cooked No.0 hamburger.
DONE!Consumer B has eaten No.0 hamburger.

cooking...
Producer A has cooked No.1 hamburger.
DONE!Consumer C has eaten No.1 hamburger.

cooking...
Producer A has cooked No.2 hamburger.
DONE!Consumer B has eaten No.2 hamburger.

cooking...
Producer A has cooked No.3 hamburger.
DONE!
Consumer C has eaten No.3 hamburger.cooking...

Producer A has cooked No.4 hamburger.
DONE!

生产者消费者模型_第3张图片

你可能感兴趣的:(Python,python)