Python中如何使用threading创建多线程后正确结束这些线程

请问一下,我用 threading 创建了几个线程去同时运行几个 cmd 的命令,但是这几个命令是不会自己结束掉的,它们一直在运行,我想做成当我输入按键事件的时候结束掉这几个线程。
例如代码这样写:

for cmd in cmds:

th = threading.Thread(target=execCmd, args=(cmd,))

th.start()

threads.append(th)
Python中如何使用threading创建多线程后正确结束这些线程

10 回复

最好别人工去关掉线程吧,一定要关的话可以自己写一个 stop()或者用 multiprocessing 用多进程实现任务。
写 stop 的话可以参考
https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python


在Python里用threading搞多线程,想优雅结束线程,得用标志位配合threading.Event。别用那个废弃的Thread.stop(),会出乱子。

看这个例子,我们搞个能响应停止信号的worker线程:

import threading
import time

class StoppableThread(threading.Thread):
    def __init__(self):
        super().__init__()
        self._stop_event = threading.Event()
    
    def run(self):
        while not self._stop_event.is_set():
            print(f"{self.name} is running...")
            time.sleep(1)
        print(f"{self.name} is stopping...")
    
    def stop(self):
        self._stop_event.set()
        self.join()  # 等待线程结束

# 创建并启动线程
threads = []
for i in range(3):
    t = StoppableThread()
    t.start()
    threads.append(t)

# 让线程跑一会儿
time.sleep(3)

# 优雅停止所有线程
print("\nStopping all threads...")
for t in threads:
    t.stop()

print("All threads stopped.")

关键点:

  1. 每个线程自己带个Event标志
  2. run()方法里循环检查这个标志
  3. 外部调用stop()设置标志,线程自己就会退出循环
  4. 最后join()确保线程完全结束

如果线程卡在IO操作上,得用带超时的select或者signal来中断。对于计算密集型的,得定期检查停止标志。

简单说就是:用Event标志让线程自己退出最靠谱。

那如果使用 multiprocessing 呢?

设置一个事件或者变量,告诉那个线程该结束了,然后等这个线程结束。

注意,杀死一个 cmd 进程不等同于杀死创建该进程的线程,后者可能会导致当前进程坏掉。

我刚上手 python 不久,您能详细描述一下吗,要使用那些方法或函数?

Thread.setDaemon(true)

具体到你的代码就是:
th.setDaemon(True)
th.start()

multiprocessing 是 python 内置一个多进程模块,网上有相应的教程的

重写 run 和 stop,留个变量 flag
def run:
while(flag):
Do something
def stop:
flag = false
或者用 setdaemon

嗯,但如果使用 setdaemon 就有个问题,我想结束掉这几个子线程之后我的主线程下面还要继续执行,程序还没结束呢?

回到顶部