python 生产者消费者模型,python asyncio 生产者消费者模型实现

网上看到的生产者消费者的代码大部分都是执行有限次数的。最近项目中用到类型业务模型。也就模仿的写了一个。该代码生产者每2秒生产一个值,消费者每1秒消费一个值。

import asyncio

class Test(object):

def __init__(self, loop=None):

self._queue = asyncio.Queue(loop=loop)

self._future = asyncio.Future(loop=loop)

async def _producer(self, interval):

v = 0

while True:

await asyncio.sleep(interval)

print('add value to queue:',str(v))

await self._queue.put(v)

v = v + 1

async def _consumer(self):

while True:

try:

r =await  asyncio.wait_for(self._queue.get(), timeout=1.0)

# r = await self._queue.get()

print('consumer value>>>>>>>>>>>>>>>>>>', r)

except asyncio.TimeoutError:

print('get value timeout')

continue

except:

break

print('quit')

async def run(self):

asyncio.ensure_future(self._producer(2))

asyncio.ensure_future(self._consumer())

loop = asyncio.get_event_loop()

t = Test(loop=loop)

asyncio.ensure_future(t.run())

try:

loop.run_forever()

except KeyboardInterrupt as e:

print(asyncio.Task.all_tasks())

for task in asyncio.Task.all_tasks():

print(task.cancel())

loop.stop()

loop.run_forever()

finally:

loop.close()

输出结果:

get value timeout

add value to queue: 0

consumer value>>>>>>>>>>>>>>>>>> 0

get value timeout

add value to queue: 1

get value timeout

consumer value>>>>>>>>>>>>>>>>>> 1

get value timeout

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值