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()
全部评论
异步返回的是对象,同步返回的才是结果,同步返回需要await
点赞
送花
回复
分享
发布于 2020-01-17 22:03

相关推荐

头像
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务