gpt4 book ai didi

python - 在 curio 中等待事件的问题

转载 作者:行者123 更新时间:2023-11-28 17:59:29 25 4
gpt4 key购买 nike

我正在使用 curio 来实现两个任务的机制,这两个任务使用 curio.Event 对象进行通信。第一个任务(称为 action())首先运行,并且 等待 事件被设置。第二个任务(称为 setter())在第一个任务之后运行,并设置事件。

代码如下:

import curio

evt = curio.Event()


async def action():
await evt.wait()
print('Performing action')


async def setter():
await evt.set()
print('Event set')


async def run():
task = await curio.spawn(action())
await setter()
print('Finished run')
await task.wait()


curio.run(run())

输出如下:

Event set
Finished run
Performing action

这意味着 print('Performing action')print('Finished run') 之后执行,这就是我试图阻止的 - 我是期望调用 await evt.set() 也会调用它的所有服务员,并且 run() 不会继续,直到所有服务员都被调用,这意味着 action() 将在执行 print('Finished run') 之前继续执行。这是我想要的输出:

Event set
Performing action
Finished run

我哪里错了?有什么办法可以改变这种行为吗?我想更好地控制执行顺序。

谢谢

最佳答案

设置 Event 是一种表示某事发生的方式:正如您已经注意到的那样,它不提供服务员的调用。

如果你想在执行操作后报告运行完成,你应该在等待操作后报告它:

async def run():
task = await curio.spawn(action())
await setter()
await task.wait() # await action been performed
print('Finished run') # and only after that reporting run() is done

如果你想阻止 run() 的执行,直到有事情发生,你可以用另一个事件 wait() 来完成,它应该是 set() 当这件事发生时:

import curio

evt = curio.Event()
evt2 = curio.Event()


async def action():
await evt.wait()
print('Performing action')
await evt2.set()
print('Event 2 set')


async def setter():
await evt.set()
print('Event set')


async def run():
task = await curio.spawn(action())
await setter()
await evt2.wait()
print('Finished run')
await task.wait()


curio.run(run())

回复:

Event set
Performing action
Event 2 set
Finished run

关于python - 在 curio 中等待事件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56485408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com