threading.Condition()用法

本文介绍了一个基于Python的生产者消费者模型实现,通过使用线程和条件变量,模拟了生产者和消费者之间的同步过程。生产者负责生产商品,而消费者负责消费商品,两者通过一个共享的缓冲区进行交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import threading
import time
from decimal import Decimal

condition = threading.Condition()
num = 0
box_size=15

class GoodsProduce(threading.Thread):
    def __init__(self,companyName,produceSpeed,info):
        super(GoodsProduce,self).__init__()
        self.companyName=companyName
        self.produceSpeed=Decimal(2/produceSpeed).quantize(Decimal('0.00'))
        self.info=info

    def run(self):
        global num
        while True:
            if condition.acquire():
                if num < box_size:
                    time.sleep(self.produceSpeed)
                    num += 1;
                    print("GoodsProduce : %s create one , now box have :%d" %(self.companyName, num))
                    condition.notify()
                    condition.release()
                else:
                    print("NOTE: BOX is full , size %d ,filled %d" %(box_size, num))
                    condition.wait();

    def show(self):
        print("companyName -- %s ,produceSpeed -- %s, infomation -- %s"%(self.companyName,self.produceSpeed,self.info))

class GoodsConsume(threading.Thread):
    def __init__(self,cname,area,info):
        super(GoodsConsume,self).__init__()
        self.cname=cname
        self.area=area
        self.info=info

    def run(self):
        global num
        while True:
            if condition.acquire():
                if num >= 1:
                    num -= 1
                    print("GoodsConsumer %s get one , now box have :%d" %(self.cname,num))
                    condition.notify()
                    condition.release()
                else:
                    print("NOTE: BOX is null ,please wait ...  size %d ,fillin %d" % (box_size, num))
                    time.sleep(1)
                    condition.wait();
                time.sleep(1)
    def show(self):
        print("GoodsConsume %s area -- %s ,infomation -- %s"%(self.cname,self.area,self.info))


if __name__ == "__main__":
    for server_num in range(0, 2):
        server = GoodsProduce("Prd-%d"%server_num,server_num+1,"this is %d prd company"%server_num)
        server.start()
        server.show()

    for customer_num in range(0, 5):
        customer = GoodsConsume("cus-%d"%customer_num,"area-%d"%customer_num,"this is %d customer"%customer_num)
        customer.start()
        customer.show()
import threading
import time

task = []

class Producer(threading.Thread):   # 创建threading.Thread的子类来包装一个线程对象
   def run(self):
       while True:
           if con.acquire():
               print("producer role")
               if len(task) >500:
                   con.wait()
               else:
                   for i in range(100):
                       task.append(i)
                   msg = self.name+' produce 100, count=' + str(len(task))
                   print(msg)
                   # con.notify()
                   time.sleep(5)
                   con.release()

class Consumer(threading.Thread):
   def run(self):
       while True:
           if con.acquire():
               print("consumer role")
               if len(task) < 100:
                   con.wait()
               else:
                   for i in range(50):
                       task.pop()
                   msg = self.name+' consume 3, count='+str(len(task))
                   print(msg)
                   con.notify()
                   time.sleep(3)
                   con.release()

con = threading.Condition()

def test():
    for i in range(2):
        p = Producer()
        p.start()
    for i in range(5):
        c = Consumer()
        c.start()
if __name__ == '__main__':
    test()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值