Python 3.7 - asyncio.sleep() and time.sleep()

后端 未结 1 1204
栀梦
栀梦 2020-12-09 01:45

When I go to the asyncio page, the first example is a hello world program. When I run it on python 3.73, I can\'t see any different from the normal

相关标签:
1条回答
  • 2020-12-09 02:12

    You aren't seeing anything special because there's nothing much asynchronous work in your code. However, the main difference is that time.sleep(5) is blocking, and asyncio.sleep(5) is non-blocking.

    When time.sleep(5) is called, it will block the entire execution of the script and it will be put on hold, just frozen, doing nothing. But when you call await asyncio.sleep(5), it will ask the event loop to run something else while your await statement finishes its execution.

    Here's an improved example.

    import asyncio
    
    async def hello():
        print('Hello ...')
        await asyncio.sleep(5)
        print('... World!')
    
    async def main():
        await asyncio.gather(hello(), hello())
    
    asyncio.run(main())
    

    Will output:

    ~$ python3.7 async.py
    Hello ...
    Hello ...
    ... World!
    ... World!
    

    You can see that await asyncio.sleep(5) is not blocking the execution of the script.

    Hope it helps :)

    0 讨论(0)
提交回复
热议问题