Pythonでスレッドを強制終了する問題について、高度に解決された解決策を理解しようとしています:Is there any way to kill a Thread in Python?。著者はクラスStoppableThread
を提供し、それをどのように使用するか(すなわち、stop()
メソッドを呼び出し、join()
を使用してスレッドが正常に終了するのを待って)説明します。PythonのスレッディングのStoppableThreadサブクラスの使用例
私は簡単な例を使って、この仕事をするために試してみた:
import time
import threading
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self, *args, **kwargs):
super(StoppableThread, self).__init__(*args, **kwargs)
self._stop = threading.Event()
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
def run_forever():
while True:
print("Hello, world!")
time.sleep(1)
thread = StoppableThread(target=run_forever)
thread.start()
time.sleep(5)
thread.stop()
thread.join()
は私がthread
が停止される前に、プログラムがHello, world!
の約5倍を印刷することを期待します。しかし、私が見ていることは、それが無期限に印刷を続けることだけです。
誰かがStoppableThread
サブクラスの正しい使い方を明確にすることはできますか?
おそらくコード全体を含めることはできますか? 'run_forever'を' StoppableThread'のクラスメソッド( 'self'を使うために必要です)にすると' thread = StoppableThread(target = run_forever) 'をしようとすると' NameError'が出ます。 –
私は完全なコードを追加しました。私はちょうどあなたがあなたのrunメソッドの名前を変更してスレッドの外に置いたことに気付きました。上記(おそらく)は動作します。また、ターゲットキーワードパラメータは必要ありません。 – Hannu
アプリケーションにいくつかの停止可能なスレッドを配置する予定の場合、StoppableThreadをサブクラス化する別のコードスニペットを追加しました。 – Hannu