python 多线程笔记(6)-- 生产者/消费者模式(续)

简介: 用 threading.Event() 也可以实现生产者/消费者模式 (自己拍脑袋想出来的,无法知道其正确性,请大神告知为谢!)   import threading import time import random products = 20 class Producer(threading.

 

用 threading.Event() 也可以实现生产者/消费者模式

(自己拍脑袋想出来的,无法知道其正确性,请大神告知为谢!)

 

import threading
import time
import random


products = 20

 
class Producer(threading.Thread):
    '''生产者'''
    ix = [0] # 生产者实例个数
             # 闭包,必须是数组,不能直接 ix = 0
    
    def __init__(self):
        super().__init__()
        self.ix[0] += 1
        self.setName('生产者' + str(self.ix[0]))
 
    def run(self):
        global producer_signal, products
        
        while True:
            if products < 10:
                if not producer_signal.is_set(): producer_signal.set()
                products += 1;
                print("{}:库存告急。我努力生产了1件产品,现在产品总数量 {}".format(self.getName(), products))
            else:
                print("{}:库存充足。我努力生产了0件产品,现在产品总数量 {}".format(self.getName(), products))
                if producer_signal.is_set(): producer_signal.wait()
            time.sleep(random.randrange(1,4))
        
        
class Consumer(threading.Thread):
    '''消费者'''
    ix = [0] # 消费者实例个数
             # 闭包,必须是数组,不能直接 ix = 0
             
    def __init__(self):
        super().__init__()
        self.ix[0] += 1
        self.setName('消费者' + str(self.ix[0]))
 
    def run(self):
        global consumer_signal, products
        
        while True:
            if products > 1:
                if not consumer_signal.is_set(): consumer_signal.set()
                products -= 1;
                print("{}:我消费了1件产品,现在产品数量 {}".format(self.getName(), products))
            else:
                print("{}:我消费了0件产品。现在产品数量 {}".format(self.getName(), products))
                if consumer_signal.is_set(): consumer_signal.wait()
            time.sleep(random.randrange(2,6))
 

        
        
if __name__ == "__main__":

    producer_signal = threading.Event()
    consumer_signal = threading.Event()
    
    for i in range(2):
        p = Producer()
        p.start()
 
    for i in range(10):
        c = Consumer()
        c.start()
 

 

目录
相关文章
|
5天前
|
安全 Java 数据处理
Python网络编程基础(Socket编程)多线程/多进程服务器编程
【4月更文挑战第11天】在网络编程中,随着客户端数量的增加,服务器的处理能力成为了一个重要的考量因素。为了处理多个客户端的并发请求,我们通常需要采用多线程或多进程的方式。在本章中,我们将探讨多线程/多进程服务器编程的概念,并通过一个多线程服务器的示例来演示其实现。
|
15天前
|
算法 数据处理 Python
Python并发编程:解密异步IO与多线程
本文将深入探讨Python中的并发编程技术,重点介绍异步IO和多线程两种常见的并发模型。通过对比它们的特点、适用场景和实现方式,帮助读者更好地理解并发编程的核心概念,并掌握在不同场景下选择合适的并发模型的方法。
|
14天前
|
数据采集 安全 Python
python并发编程:Python实现生产者消费者爬虫
python并发编程:Python实现生产者消费者爬虫
22 0
python并发编程:Python实现生产者消费者爬虫
|
14天前
|
数据采集 Java API
python并发编程: Python使用线程池在Web服务中实现加速
python并发编程: Python使用线程池在Web服务中实现加速
17 3
python并发编程: Python使用线程池在Web服务中实现加速
|
17天前
|
Java 测试技术 Python
Python开启线程和线程池的方法
Python开启线程和线程池的方法
12 0
Python开启线程和线程池的方法
|
Python Windows Linux