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

2024-05-12 19:34:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Jupyter笔记本上运行了一个长时间的计算,python生成的一个线程(我怀疑是pickle.dump调用)占用了所有可用的RAM,使系统变得笨拙。你知道吗

现在,我想终止单线程。中断笔记本不工作,我不想重新启动笔记本,以不失去所有的计算到目前为止。如果我打开活动监视器,我可以清楚地看到一个包含多个线程的python进程。你知道吗

我知道我可以终止整个进程,但是有没有办法终止一个线程?你知道吗


Tags: 进程系统笔记本jupyter线程dumppickleram
2条回答

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

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

相关问题 更多 >