【问题标题】:How to wait on multiple conditions simultaneously until any of them returns true如何同时等待多个条件,直到其中任何一个返回 true
【发布时间】:2021-01-17 13:55:12
【问题描述】:

这是我的代码:

async def fun1():
   result=False
   #Some time-consuming operations...
   return result

async def fun2():
  result=False
  #Some time-consuming operations...
  return result

if fun1() or fun2():
  print("Success")

if 块按顺序运行所有条件,但我想同时运行它们并等到 任何主题 返回 True。我知道asyncio.wait(tasks,return_when=asyncio.FIRST_COMPLETED),但我不知道如何将其用于我的目的。

【问题讨论】:

  • 你能用while True: if fun1() or fun2(): break else: sleep(sometime)吗?

标签: python if-statement asynchronous parallel-processing python-asyncio


【解决方案1】:

你可以使用asyncio.ensure_future:

根据您展示的内容改编的代码示例:

import asyncio, time, random 

async def fun1():
    result = False
    # Some time-consuming operations...
    result = random.randint(1, 10)
    await asyncio.sleep(result)
    return result

async def fun2():
    result = False
    # Some time-consuming operations...
    result = random.randint(1, 10)
    await asyncio.sleep(result)
    return result

async def main():
    t1 = asyncio.ensure_future(fun1())
    t2 = asyncio.ensure_future(fun2())

    count = 0
    while not any([t1.done(), t2.done()]):
        print(f'{count} - {t1.done()}, {t2.done()}')
        await asyncio.sleep(1)
        count += 1

    print(f'At least one task is done: {t1.done()}, {t2.done()}')

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

仅作为提醒,如果 main 在任何任务完成执行之前结束,此代码可能会触发消息。可能执行的示例:

0 - False, False
1 - False, False
At least one task is done: False, True
Task was destroyed but it is pending!
task: <Task pending name='Task-2' coro=<fun1() running at /tmp:7> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x00000239C83B4B50>()]>>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-29
    • 2021-04-28
    • 2022-09-27
    相关资源
    最近更新 更多