在 curio 中等待事件的问题
Issue with waiting for an Event in curio
我正在使用 curio
来实现使用 curio.Event
对象进行通信的两个任务的机制。第一个任务(称为 action()
)首先运行,awaits
是要设置的事件。第二个任务(称为 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
我正在使用 curio
来实现使用 curio.Event
对象进行通信的两个任务的机制。第一个任务(称为 action()
)首先运行,awaits
是要设置的事件。第二个任务(称为 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