|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
下面是2个不同的封装方式, 但是线程的使用却有明显的不同,一个是可以乱序的,一个是按顺序执行的,求大神解答。 不知道原因。
import asyncio
import time
async def ceshi01(x,y):
await asyncio.sleep(y)
print(f"我是{x},我运行了{y}分钟")
async def yunxing():
group_a = asyncio.gather(ceshi01('A',5),ceshi01('a',3)) #线程a
group_b = asyncio.gather(ceshi01('b',4),ceshi01('B',2)) #线程b
await group_a
await group_b
print(asyncio.run(yunxing()))
运行结果是: 结果是按时间排序的, 效率最高。
我是B,我运行了2分钟
我是a,我运行了3分钟
我是b,我运行了4分钟
我是A,我运行了5分钟
另外一个封装方式
import asyncio
import time
async def ceshi01(x,y):
await asyncio.sleep(y)
print(f"我是{x},我运行了{y}分钟")
async def yunxing():
await asyncio.gather(ceshi01('A',5),ceshi01('a',3))
await asyncio.gather(ceshi01('b',4),ceshi01('B',2))
await asyncio.gather(ceshi01('c',1),ceshi01('c',1))
print(asyncio.run(yunxing()))
运行结果是: 这里的结果是按顺序执行的 从a到c
我是a,我运行了3分钟
我是A,我运行了5分钟
我是B,我运行了2分钟
我是b,我运行了4分钟
我是c,我运行了1分钟
我是c,我运行了1分钟 |
|