【问题标题】:macOS, is it possible to terminate a single python thread?macOS,是否可以终止单个 python 线程?
【发布时间】:2019-06-06 05:03:56
【问题描述】:

我正在 Jupyter 笔记本上运行长时间计算,其中一个由 py​​thon 产生的线程(我怀疑是 pickle.dump 调用)占用了所有可用的 RAM,使系统变得笨拙。

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

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

【问题讨论】:

  • 您想从正在运行的代码中终止线程您希望从操作系统外部终止线程吗?
  • @Francesco 来自操作系统

标签: python python-3.x terminate


【解决方案1】:

我认为你不能在进程本身之外杀死进程的线程:

this answer报道的那样

线程是进程不可分割的一部分,不能被杀死 在它之外。有pthread_kill 功能,但它仅适用于 thread itself 的上下文。来自链接上的文档

【讨论】:

  • 我怀疑,多么不幸。感谢您的回答。
  • 很好的问题,虽然它让我想到了 :)
【解决方案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

【讨论】:

  • 这不能解决问题。我想停止当前正在运行的线程,而不是实现一个新的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-29
  • 1970-01-01
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多