Python MultiProducer and MultiConsumer

生产者消费者模式
本文通过Python的threading模块实现了一个生产者消费者模型的例子。利用Condition条件变量同步多个线程的操作,确保生产者线程和消费者线程之间的正确交互。当产品数量少于10时,生产者线程生产产品;当产品数量大于等于10时,消费者线程可以消费产品。
import threading
import time

condition = threading.Condition() #Condition被称为条件变量,除了提供与Lock类似的acquire和release方法外,还提供了wait和notify方法
products = 0

class Producer(threading.Thread):
    '''生产者'''
    ix = [0] # 生产者实例个数
                # 闭包,必须是数组,不能直接 ix = 0
    def __init__(self, ix=0):
        threading.Thread.__init__(self)
        self.ix[0] += 1
        self.setName('生产者' + str(self.ix[0]))

    def run(self):
        global condition, products

        while True:
            if condition.acquire():
                if products < 10:
                    products += 1;
                    print("{}:库存不足(10-)。我努力生产了1件产品,现在产品总数量 {}".format(self.getName(), products))
                    condition.notify()
                else:
                    print("{}:库存充足(10+)。让我休息会儿,现在产品总数量 {}".format(self.getName(), products))
                    condition.wait();
                condition.release()
                #time.sleep(2)


class Consumer(threading.Thread):
    '''消费者'''
    ix = [0] # 消费者实例个数
                # 闭包,必须是数组,不能直接 ix = 0
    def __init__(self):
        threading.Thread.__init__(self)
        self.ix[0] += 1
        self.setName('消费者' + str(self.ix[0]))

    def run(self):
        global condition, products

        while True:
            if condition.acquire():
                if products > 1:
                    products -= 1
                    print("{}:我消费了1件产品,现在产品数量 {}".format(self.getName(), products))
                    condition.notify()
                else:
                    print("{}:只剩下1件产品,我停止消费。现在产品数量 {}".format(self.getName(), products))
                    condition.wait();
                condition.release()
                time.sleep(5)



if __name__ == "__main__":
    for i in range(5):
        p = Producer()
        p.start()

    for i in range(10):
        c = Consumer()
        c.start()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值