美文网首页
python3 asyncio

python3 asyncio

作者: 草帽lufei | 来源:发表于2019-10-12 19:24 被阅读0次
    1. 引入 asyncio 模块
    import asyncio
    
    1. 定义一个协程函数
    async def do_something(x):
        print('waiting: ', x)
    
        await asyncio.sleep(x)
        return x
    
    
    1. 协程不能直接运行,把协程加入到事件循环(loop)。asyncio.get_event_loop 方法可以创建一个事件循环,然后使用 run_until_complete 将协程注册到事件循环,并启动事件循环。
      使用 asyncio.ensure_future(coroutine) 创建 task ,方便在后面读取任务结果
    coroutine1 = do_something(1)
    coroutine2 = do_something(4)
    
    tasks = [
        asyncio.ensure_future(coroutine1),
        asyncio.ensure_future(coroutine2)
    ]
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))
    
    1. 获取 task 执行结果,并打印
    for task in tasks:
        print('task result: ', task.result())
    

    main.py 完整例子

    import asyncio
    
    import time
    print('1')
    now = lambda: time.time()
    
    async def do_something(x):
        print('waiting: ', x)
    
        await asyncio.sleep(x)
        return x
    
    start = now()
    print('2')
    coroutine1 = do_something(1)
    coroutine2 = do_something(4)
    
    tasks = [
        asyncio.ensure_future(coroutine1),
        asyncio.ensure_future(coroutine2)
    ]
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))
    
    print('123')
    time.sleep(10)
    print('333333')
    
    
    for task in tasks:
        print('task result: ', task.result())
    
    print('time: ', now() - start)
    
    

    相关文章

      网友评论

          本文标题:python3 asyncio

          本文链接:https://www.haomeiwen.com/subject/gsvdhqtx.html