如何同时运行Watching配置中启用的Watcher?线程方案未生效
解决多Watcher同时运行的线程实现问题
问题核心
需要让watching_config中设为True的所有Watcher同时运行,原线程尝试代码存在逻辑错误,导致无法实现多线程并发。
原代码问题分析
线程尝试代码中,启动Watcher线程后嵌套了while True循环,这会导致:
- 单个Watcher被反复创建并启动,造成资源浪费
- 主线程卡在当前Watcher的循环中,无法继续启动其他Watcher
修正后的代码
import threading # 假设已导入WindowsDefender、WindowsFirewall、sys、time、colors、clear、banner等模块 watching_config = { "WindowsDefender": False, "WindowsFirewall": False } def main(): divider = "-" * 20 while True: clear() for char in banner: sys.stdout.write(char) sys.stdout.flush() time.sleep(0.0001) print(colors.blue + "\n\n" + divider + " | LogSentry Watching | " + divider + colors.reset) print(f"{colors.blue}1. Windows Defender: " + str(watching_config["WindowsDefender"]) + f"{colors.reset}") print(f"{colors.blue}2. Windows Firewall: " + str(watching_config["WindowsFirewall"]) + f"{colors.reset}") print(f"{colors.blue}3. Start LogSentry{colors.reset}") choice = input("\nEnter your choice: ") if choice == "1": watching_config["WindowsDefender"] = not watching_config["WindowsDefender"] elif choice == "2": watching_config["WindowsFirewall"] = not watching_config["WindowsFirewall"] elif choice == "3": watcher_threads = [] # 遍历配置,启动所有需要运行的Watcher线程 for key, value in watching_config.items(): if value: print(f"\n{colors.green}Starting {key} watcher...{colors.reset}") try: if key == "WindowsDefender": thread = threading.Thread(target=WindowsDefender.Watch, daemon=True) thread.start() watcher_threads.append(thread) elif key == "WindowsFirewall": thread = threading.Thread(target=WindowsFirewall.Watch, daemon=True) thread.start() watcher_threads.append(thread) else: print(f"{colors.red}Invalid watcher!{colors.reset}") except Exception as e: print(f"{colors.red}Failed to start {key} watcher: {str(e)}{colors.reset}") # 等待所有线程,同时捕获中断信号 try: for thread in watcher_threads: thread.join() except KeyboardInterrupt: print(f"\n{colors.red}Stopping all watchers...{colors.reset}") # 如果Watcher提供了停止方法,可以在这里调用,例如: # WindowsDefender.stop() # WindowsFirewall.stop() print(f"{colors.red}All watchers stopped!{colors.reset}")
关键修改点
- 移除了启动线程后的
while True循环,避免重复创建线程 - 使用
watcher_threads列表保存线程对象,便于统一管理 - 设置线程为
daemon=True,确保主线程退出时子线程也能自动退出 - 将线程启动逻辑从循环中移出,一次遍历即可启动所有需要的Watcher
- 统一处理KeyboardInterrupt,实现批量停止所有Watcher
内容的提问来源于stack exchange,提问作者iUseYahoo
相关产品推荐
相关产品推荐

