[英]macOS, is it possible to terminate a single python thread?
我在 Jupyter 筆記本上運行了一個很長的計算,python 產生的一個線程(我懷疑是pickle.dump
調用)占用了所有可用的 RAM,使系統變得笨拙。
現在,我想終止單線程。 中斷筆記本不起作用,我不想重新啟動筆記本,以免丟失迄今為止所做的所有計算。 如果我打開活動監視器,我可以清楚地看到一個包含多個線程的 python 進程。
我知道我可以終止整個過程,但是有沒有辦法終止單個線程?
我認為您不能在進程本身之外殺死進程的線程:
線程是進程的一個組成部分,不能在進程之外被殺死。 有
pthread_kill
函數,但它只適用於thread itself
的上下文。 來自鏈接中的文檔
當然答案是肯定的,我有一個演示代碼僅供參考(不安全):
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.