[英]Python asyncio: function or coroutine, which to use?
I'm wondering if there are any noticeable differences in performance between foo
and bar
: 我想知道
foo
和bar
之间的性能是否有任何明显的区别:
class Interface:
def __init__(self, loop):
self.loop = loop
def foo(self, a, b):
return self.loop.run_until_complete(self.bar(a, b))
async def bar(self, a, b):
v1 = await do_async_thing1(a)
for i in range(whatever):
do_some_syncronous_work(i)
v2 = await do_async_thing2(b, v1)
return v2
async def call_foo_bar(loop):
a = 'squid'
b = 'ink'
interface = Interface(loop)
v_foo = interface.foo(a, b)
v_bar = await interface.bar(a, b)
But will the use of run_until_complete
cause any practical, noticeable different to running my program? 但是,使用
run_until_complete
会导致与运行我的程序有任何实际的,明显的不同?
(The reason I ask is I'm building an interface class which will accommodate decomposable "back-ends" some of which could be asynchronous. I'm hoping to use standard functions for the public (reusable) methods of the interface class so one API can be maintained for all code without messing up the use of asynchronous back-ends where an event-loop is available.) (我问的原因是我正在构建一个接口类,以容纳可分解的“后端”,其中某些后端可能是异步的。我希望为接口类的公共(可重用)方法使用标准函数,因此可以为所有代码维护API,而不会弄乱使用事件循环可用的异步后端。)
Update: I didn't check the code properly and the first version was completely invalid, hence rewrite. 更新:我没有正确检查代码,第一个版本完全无效,因此被重写。
loop.run_until_complete()
should be used outside of coroutine on very top level. loop.run_until_complete()
应该在协程之外的最顶层使用。 Calling run_until_complete()
with active (running) event loop is forbidden. 禁止在活动 (运行)事件循环中调用
run_until_complete()
。
Also loop.run_until_complete(f)
is a blocking call: execution thread is blocked until f
coroutine or future becomes done. 此外,
loop.run_until_complete(f)
是一个阻塞调用:执行线程被阻塞,直到f
协程或将来完成为止。
async def
is a proper way to write asynchronous code by making concurrent coroutines which may communicate with each other. async def
是通过编写可能相互通信的并发协程来编写异步代码的正确方法。
async def
requires running event loop (either loop.run_until_complete()
or loop.run_forever()
should be called). async def
需要运行事件循环(应该调用loop.run_until_complete()
或loop.run_forever()
)。
There is a world of difference. 有一个不同的世界。 It is a
SyntaxError
to use await
in a normal function def
function. 在常规函数
def
函数中使用await
是SyntaxError
。
import asyncio
async def atest():
print("hello")
def test():
await atest()
async def main():
await atest()
test()
-- -
File "test.py", line 9
await atest()
^
SyntaxError: invalid syntax
I do not believe so. 我不相信。 I have used both and have not really seen a difference.
我都用过,还没有真正看到区别。 I prefer foo just because I have used it more and understand it a bit better, but it is up to you.
我更喜欢foo,只是因为我已经使用了更多的代码,并且对它的了解有所了解,但这取决于您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.