asyncio.Event在信号处理程序中未被设置
创始人
2024-09-21 05:00:55
0

在实现信号处理程序的函数中,不能直接设置 asyncio.Event 实例的状态,必须通过调用 asyncio.ensure_future() 来执行协程,并在协程中设置 Event 的状态。以下是一个示例:

import asyncio
import signal

loop = asyncio.get_event_loop()
evt = asyncio.Event()

async def do_work():
    print("Starting work ...")
    await asyncio.sleep(3)
    print("Work finished.")
    evt.set()

async def signal_handler():
    print("Received signal, stopping tasks ...")
    task = asyncio.ensure_future(do_work())
    await evt.wait()
    task.cancel()
    print("All tasks stopped.")
    loop.stop()

async def main():
    # Register the signal handler
    loop.add_signal_handler(signal.SIGINT, lambda: asyncio.ensure_future(signal_handler()))

    # Start main work
    await asyncio.gather(do_work())

if __name__ == "__main__":
    loop.run_until_complete(main())

在上面的示例中,signal_handler() 函数是信号处理程序,它会调用 asyncio.ensure_future() 来启动协程 do_work(),并在协程中设置 Event 的状态。当 Event 的状态被设置后,signal_handler() 会取消任务并关闭事件循环。

相关内容

热门资讯

we poker辅助器下载!来... we poker辅助器下载!来玩德州破解器(透视)神器-总是辅助真的有挂we poker辅助器下载是...
透视专业!德普之星透视辅助软件... 透视专业!德普之星透视辅助软件下载(透视)impoker辅助,教程讲义(有挂攻略)-哔哩哔哩1、完成...
hhpoker德州牛仔视频!w... hhpoker德州牛仔视频!wepoker私人局辅助(透视)方法-切实揭幕真的是有挂1、超多福利:超...
透视详细!wepoker免费脚... 透视详细!wepoker免费脚本咨询(透视)We poker辅助器下载,教程课程(有挂细节)-哔哩哔...
wepoker辅助器最新版本更... 您好,wepoker辅助器最新版本更新内容这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485...
透视必备!约局吧透视脚本(透视... 透视必备!约局吧透视脚本(透视)wepoker脚本下载,教程机巧(有挂方式)-哔哩哔哩1、打开软件启...
we poker插件!wpk模... we poker插件!wpk模拟器是什么(透视)插件-本来揭露是有挂we poker插件!wpk模拟...
透视解谜!约局吧怎么看有没有挂... 透视解谜!约局吧怎么看有没有挂(透视)模拟器打开hhpoker,教程阶段(真实有挂)-哔哩哔哩1.约...
wepoker辅助器下载!im... wepoker辅助器下载!impoker辅助(透视)插件-本来分享是有挂1、wepoker辅助器下载...
透视专业!pokermaste... 透视专业!pokermaster修改器(透视)德普之星私人局辅助器,教程法子(有挂透明挂)-哔哩哔哩...