async python - yield from raises AssertionError 以获得正确的参数

async python - yield from raises AssertionError for correct parameters

我的要求是 运行 同时执行 2 个函数,如果另一个函数计算得更快,则停止执行一个,returns 结果更快。

我了解异步编程或事件循环的知识。我读 python 3.6 which lead me to asyncio.wait()

我的示例代码:

import time
import asyncio as aio

async def f(x):
    time.sleep(1) # to fake fast work
    print("f say: " + str(x*2))
    return x*2

async def s(x):
    time.sleep(3) # to fake slow work
    print("s say: " + str(x*2))
    return x**2

x = 10

assert aio.iscoroutinefunction(f)
assert aio.iscoroutinefunction(s)

futures = {f(x), s(x)}

def executor():
    yield from aio.wait(futures, return_when=aio.FIRST_COMPLETED)

done, pending = executor()

但由于某些未知原因它不起作用。

您得到的特定断言与 yield from 的不正确使用有关。然而,问题运行更深:

My requirement is to run 2 functions at the same time

这不是 asyncio 的工作方式,什么都不是 运行 "at the same time"。相反,一个 运行s 异步函数一直执行到它们到达通常是阻塞调用的位置。异步函数不是阻塞,而是挂起它的执行,允许其他协程 运行。它们必须由 事件循环 驱动,一旦某些 IO 事件允许它们恢复,它就会驱动它们并唤醒它们。

您的代码的更正确的异步版本如下所示:

import asyncio

async def f(x):
    await asyncio.sleep(1) # to fake fast work
    print("f say: " + str(x*2))
    return x*2

async def s(x):
    await asyncio.sleep(3) # to fake slow work
    print("s say: " + str(x*2))
    return x**2

async def execute():
    futures = {f(10), s(10)}
    done, pending = await asyncio.wait(futures, return_when=asyncio.FIRST_COMPLETED)
    for fut in pending:
        fut.cancel()
    return done

loop = asyncio.get_event_loop()
done = loop.run_until_complete(execute())
print(done)

特别注意:

    使用
  • asyncio.sleep() 代替 time.sleep()。这适用于每个阻塞调用。

  • asyncio.sleepasyncio.wait 等协程必须 awaited 使用 await 关键字。这允许协程在遇到阻塞调用时自行挂起。

  • 异步代码通过事件循环执行,其入口点通常为run_until_complete or run_forever.