python怎么停止子线程

599
2023/8/18 11:36:41
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Python中,无法直接停止子线程。但可以通过设置一个标志位,在子线程中定期检查该标志位,以判断是否停止线程。以下是一个示例代码:

import threading
# 标志位,用于控制子线程是否停止
stop_flag = False
# 子线程执行的函数
def child_thread_func():
global stop_flag
while not stop_flag:
# 子线程执行的逻辑
pass
# 创建子线程
child_thread = threading.Thread(target=child_thread_func)
# 启动子线程
child_thread.start()
# 停止子线程的函数
def stop_child_thread():
global stop_flag
stop_flag = True
# 调用停止子线程的函数
stop_child_thread()

上述代码中,通过设置全局变量stop_flag作为标志位,在子线程中定期检查该标志位。当stop_flagTrue时,子线程会退出循环,从而停止线程的执行。然后通过调用stop_child_thread()函数来改变stop_flag的值,从而实现停止子线程的功能。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: vscode如何配置python运行环境