linux condition用法,threading Condition方法

主要用于生产者,消费者模型

消费者消费速度大于生产者生产速度例子

class Dispatcher:

def __init__(self):

self.data = None

self.event = threading.Event()

def produce(self, total):

for _ in range(total):

data = random.randint(0,100)

logging.info(data)

self.data = data

self.event.wait(1)

self.event.set()

def consume(self):

while not self.event.is_set():

data = self.data

logging.info("recieved {}".format(data))

self.data = None

self.event.wait(0.5)

d = Dispatcher()

p = threading.Thread(target=d.produce, args=(10, ), name='producer')

c= threading.Thread(target=d.consume, name='consumer')

c.start()

p.start()

# 消费者主动去消费,需要主动去查看下生产者有没有生产数据

使用Condition改换成通知机制

生产者生产出数据,通知消费者来消费

class Dispatcher:

def __init__(self):

self.data = None

self.event = threading.Event()

self.cond = threading.Condition()

def produce(self, total):

for _ in range(total):

data = random.randint(0,100)

with self.cond:

logging.info(data)

self.data = data

self.cond.notify(2)

# self.cond.notify_all()

self.event.wait(1)

self.event.set()

def consume(self):

while not self.event.is_set():

with self.cond:

self.cond.wait()

data = self.data

logging.info("recieved {}".format(data))

self.data = None

self.event.wait(0.5)

d = Dispatcher()

p = threading.Thread(target=d.produce, args=(10, ), name='producer')

# c= threading.Thread(target=d.consume, name='consumer')

# c.start()

for i in range(5):

c = threading.Thread(target=d.consume, name="consumer-{}".format(i))

c.start()

p.start()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值