我有以下代码:
def a:
parts = asyncio.run(b())
print(parts)
async def b():
res = await asyncio.gather(*c(i) for i in range(4))
async def c(i):
for j in range(5):
print(j, end=' ')
return i
我希望c()同时执行四次。然而,对功能以及日志进行定时表明,它们按顺序执行:
0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4
[0,1,2,3]
如何更改代码,以使c()方法并行运行4次?
仅async
在函数前面添加关键字不会使它异步。您可以尝试如下操作:
test.py:
import asyncio
def a():
parts = asyncio.run(b())
print(parts)
async def b():
return await asyncio.gather(*(c(i) for i in range(4)))
async def c(i):
for j in range(5):
await asyncio.sleep(0)
print(j, end=' ')
return i
a()
测试:
python test.py
0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 [0, 1, 2, 3]
通过添加asyncio.sleep(0)
强制异步功能将控制权交给事件循环,并允许其他协程运行。
更新:2021年2月17日星期三15:25:50
Python文档指出以下内容:
事件循环在线程(通常是主线程)中运行,并在其线程中执行所有回调和任务。当任务在事件循环中运行时,没有其他任务可以在同一线程中运行。当Task执行await表达式时,正在运行的Task被挂起,事件循环执行下一个Task。
因此,所有任务都在单个线程中运行,并且asyncio.sleep()始终挂起当前任务,从而允许其他任务运行。
请注意,并发和并行性是相似的术语,但是如果您需要使用multiprocessing在多个CPU内核上同时运行多个任务,则它们不是同一回事。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句