macOS,是否可以终止单个 python 线程?

macOS, is it possible to terminate a single python thread?

我 运行 在 Jupyter notebook 上进行了长时间的计算,python 生成的线程之一(我怀疑是 pickle.dump 调用)占用了所有可用的 RAM,使得系统笨重。

现在,我想终止单线程。中断笔记本电脑不起作用,我不想重新启动笔记本电脑,以免丢失到目前为止所做的所有计算。如果我打开 Activity 监视器,我可以清楚地看到一个包含多个线程的 python 进程。

我知道我可以终止整个进程,但有没有办法终止单个线程?

当然答案是肯定的,我有一个演示代码供参考(不安全):

from threading import Thread
import time


class MyThread(Thread):
    def __init__(self, stop):
        Thread.__init__(self)
        self.stop = stop

    def run(self):
        stop = False
        while not stop:
            print("I'm running")
            time.sleep(1)
            # if the signal is stop, break `while loop` so the thread is over.
            stop = self.stop

m = MyThread(stop=False)
m.start()
while 1:
    i = input("input S to stop\n")
    if i == "S":
        m.stop = True
        break
    else:
        continue

我认为您不能在进程本身之外终止进程的线程:

this answer

报道

Threads are an integral part of the process and cannot be killed outside it. There is the pthread_kill function but it only applies in the context of the thread itself. From the docs at the link