|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我再学习协程的时候,发现写法不一样, 竟然一种生效,一种不生效.
按下面的写法,协程不生效.总耗时4秒
import asyncio
import time
async def hello_ivan(delay,what):
await asyncio.sleep(delay)
print(what)
async def main():
print( f"开始时间:{time.strftime('%X')}" )
await asyncio.create_task(hello_ivan(3,"ivan"))# 某个高io操作 正常情况下, 需要他执行完成,才会执行lucy
await asyncio.create_task(hello_ivan(1,"lucy"))# 某个高io操作 正常情况下, 需要他执行完成,才会执行lucy
print( f"结束时间:{time.strftime('%X')}" )
asyncio.run(main())
但是按下面的写法, 协程就生效了,总耗时3秒,好诡异啊 ..................求大神告知一下原因, 他们说上面的不会同步执行, 但是明明2种写法一样啊.
import asyncio
import time
async def hello_ivan(delay,what):
await asyncio.sleep(delay)
print(what)
async def main():
task1 = asyncio.create_task(hello_ivan(3,"ivan"))
task2 = asyncio.create_task(hello_ivan(1,"lucy"))
print( f"开始时间:{time.strftime('%X')}" )
await task1# 某个高io操作 正常情况下, 需要他执行完成,才会执行lucy
await task2# 某个高io操作 正常情况下, 需要他执行完成,才会执行lucy
print( f"结束时间:{time.strftime('%X')}" )
asyncio.run(main()) # 耗时3秒 |
|