zoukankan      html  css  js  c++  java
  • asyncio标准库1 Hello World

    利用asyncio的event loop,编写和调度协程
    coroutine [,kəuru:'ti:n] n. 协程

    Simple coroutine(调用1个协程)

    import asyncio
    
    async def say(what, when):
        await asyncio.sleep(when)
        print(what)
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(say('hello world', 1))  # 使用run_until_complete()方法,在协程完成后中断event loop。
    loop.close()
    

    Creating tasks(调用多个协程)

    import asyncio
    
    async def say(what, when):
        await asyncio.sleep(when)
        print(what)
    
    loop = asyncio.get_event_loop()
    
    loop.create_task(say('first hello', 2))
    loop.create_task(say('second hello', 1))
    
    loop.run_forever()  # 使用run_forever()方法,协程会一直运行,不会中断event loop
    loop.close()
    

    Stopping the loop

    import asyncio
    
    async def say(what, when):
        await asyncio.sleep(when)
        print(what)
    
    async def stop_after(loop, when):
        await asyncio.sleep(when)
        loop.stop()  # 中断event loop
    
    loop = asyncio.get_event_loop()
    
    loop.create_task(say('first hello', 2))
    loop.create_task(say('second hello', 1))
    loop.create_task(say('third hello', 4))
    loop.create_task(stop_after(loop, 3))
    
    loop.run_forever()
    loop.close()
    
    # out:
    second hello
    first hello
    Task was destroyed but it is pending!
    task: <Task pending coro=<say() done, defined at e03.py:5> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7fed59595a68>()]>>
    
    # 在执行2个任务后,中断event loop,'third hello‘任务由于延迟时间4秒,未能执行。
    
  • 相关阅读:
    JDom写入XML例子
    hdu 2549
    hdu 1328
    hdu 1334
    hdu 2547
    hdu 2374
    hdu 2550
    hdu 1335
    hdu 2548
    hdu 1722
  • 原文地址:https://www.cnblogs.com/liujitao79/p/8600660.html
Copyright © 2011-2022 走看看