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() 会取消任务并关闭事件循环。

相关内容

热门资讯

九分钟辅助!hhpoker作弊... 九分钟辅助!hhpoker作弊实战视频,wpk俱乐部是真的吗,指南教程(有挂猫腻)1、hhpoker...
第九分钟辅助!wepoker软... 第九分钟辅助!wepoker软件安装包,hh poker软件,手册教程(今日头条)一、wepoker...
七分钟辅助!wepoker插件... 七分钟辅助!wepoker插件辅助,约局吧德州真的存在透视吗,大纲教程(有挂猫腻)1、约局吧德州真的...
三分钟辅助!hh poker软... 三分钟辅助!hh poker软件,wepoker线上大神,课程教程(有挂详情)1、在wepoker线...
七分钟辅助!aapoker万能... 七分钟辅助!aapoker万能辅助器,佛手大菠萝有挂吗,策略教程(有挂教程)所有人都在同一条线上,像...
8分钟辅助!wepoker私人... 8分钟辅助!wepoker私人局透视插件,约局吧透视挂下载,窍门教程(有挂方法)1、让任何用户在无需...
第1分钟辅助!we-poker... 第1分钟辅助!we-poker正规吗,xpoker辅助神器,演示教程(有挂辅助)1、下载好xpoke...
两分钟辅助!wepoker有透... 两分钟辅助!wepoker有透视底牌吗,德扑圈透视挂,办法教程(有挂规律)暗藏猫腻,小编详细说明we...
第2分钟辅助!hhpoker真... 第2分钟辅助!hhpoker真的有透视吗,wepoker看底牌,法子教程(有挂猫腻)1、许多玩家不知...
四分钟辅助!hhpoker辅助... 四分钟辅助!hhpoker辅助软件,xpoker透视辅助,要领教程(果真有挂)1、超多福利:超高返利...