python协程
python3.5之前用 yield模拟生成器
import asyncio
import random
async def add(store,name):
"""
写入数据队列
:param store: 队列的对象
:return:
"""
for i in range(5):
name = '{} - {}'.format(name,i)
await asyncio.sleep(random.randint(1,5))
await store.put(i)
print('add one ... {}, the size is {}'.format(i,store.qsize()))
async def reduce(store):
"""
从队列中删除数据
:param store:
:return:
"""
for i in range(10):
rest = await store.get()
print(' reduce one.. {0},size: {1}'.format(rest,store.qsize()))
if __name__ == '__main__':
store = asyncio.Queue(maxsize=5)
a1 = add(store,'a1')
a2 = add(store,'a2')
r1 = reduce(store)
# 添加到事件队列
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(a1,a2,r1))
loop.close()
