在居里等待事件的问题

2024-06-07 04:13:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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

我做错什么了?有没有办法改变这种行为?我想对执行令有更多的控制权。你知道吗

谢谢


Tags: runeventcurioasyncdef事件actionawait
1条回答
网友
1楼 · 发布于 2024-06-07 04:13:08

设置Event是一种表示发生了什么的方法:正如您已经注意到的,它不提供对服务生的调用。你知道吗

如果要在执行操作后报告run finished,则应在等待操作后报告:

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

相关问题 更多 >