Python异步功能

割让

我试图弄清楚异步功能如何在Python中工作。我看了无数视频,但我想我不是在“了解”它。我的代码如下所示:

def run_watchers():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(watcher_helper())
    loop.close()

async def watcher_helper():
    watchers = Watcher.objects.all()

    for watcher in watchers:
        print("Running watcher : " + str(watcher.pk))
        await watcher_helper2(watcher)

async def watcher_helper2(watcher):
    for i in range(1,1000000):
        x = i * 1000 / 2000

对我来说有意义的是具有三个功能。一个开始循环,第二个遍历不同的选项以执行,第三个完成工作。

我期望以下输出:

Running watcher : 1
Running watcher : 2
...
...

Calculation done
Calculation done
...
...

但是我得到:

Running watcher : 1
Calculation done
Running watcher : 2
Calculation done
...
...

这显然表明计算不是并行进行的。知道我在做什么错吗?

米哈伊尔·杰拉西莫夫(Mikhail Gerasimov)

asyncio只能用于加速与网络I / O相关的多个功能(通过Internet发送/接收数据)。等待网络中的某些数据时(这可能需要很长时间),通常会闲置。使用asyncio使您可以将此空闲时间用于其他有用的工作:例如,启动另一个并行网络请求。

asyncio无法以某种方式加快与CPU相关的工作(watcher_helper2在您的示例中就是这样)。当您将一些数字相乘时,根本没有空闲时间可以用来做不同的事情并从中获得收益。

另请阅读此答案以获取更详细的说明。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章