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

相关推荐

LZStarV:冲就好了,就算真的是字节也冲,面评脏了大不了等三四个月就淡了,而且等到那个时候实力进步了选择还多,何必拘泥于字节
点赞 评论 收藏
分享
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
12-04 04:26
小红书 内容风控工程 (n+3) * 16 硕士985
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务