使用 asyncio 创建和处理条件

create and handle conditions with asyncio

我有一个父函数,它应该 运行 对数据集进行 2 次测试。 如果这些测试中的任何一个失败,父函数应该 return 失败。我想 运行 这两个测试与 asyncio 异步进行,一旦其中一个测试失败,父函数应该 return 失败并取消另一个测试。
我是 asyncio 的新手,阅读了一些带有条件 here 的示例,但无法弄清楚如何编写带条件的 asyncio。
到目前为止,我可以通过在任何失败的测试中抛出异常来处理它。
这是我的基本代码:

async def test1(data):
    # run some test on data and return true on pass and throw exception on fail

async def test2(data):
    # run some test on data and return true on pass and throw exception on fail


ioloop = asyncio.get_event_loop()
tasks = [ioloop.create_task(test1(data)), ioloop.create_task(test2(data))]
finished, unfinished = ioloop.run_until_complete(asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION))

但我认为这不是处理条件的正确方法。
所以我想要一个基本示例,说明如何使用 ayncio.

创建和处理条件

as soon as one of the tests failed, parent function should return fail and cancel the other test.

asyncio.gather 自动执行:

loop = asyncio.get_event_loop()
tasks = [loop.create_task(test1(data)), loop.create_task(test2(data))]
try:
    loop.run_until_complete(asyncio.gather(*tasks))
except FailException:  # use exception raised by the task that fails
    print('failed')

asyncio.gather 中执行的任何任务引发异常时,所有其他任务将使用 Task.cancel 取消,并且异常将传播到 gather 的等待者。您根本不需要 Condition,取消将自动中断任务正在等待的任何阻塞操作。

当空闲任务(或许多此类任务)需要等待其他任务中可能发生的事件时,需要条件。在那种情况下,它会等待一个条件,并通知它的发生。如果任务只是为了它的业务,您可以随时取消它,或者让 asyncio.gatherasyncio.wait_for 等函数为您完成。