Pythonでスレッドを停止する方法は、threading.Threadを使用することですか。

Pythonでは、フラグ変数を設定することで、スレッドの実行を停止することができます。例を以下に示す。

import threading

class MyThread(threading.Thread):
    def __init__(self):
        super().__init__()
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def run(self):
        while not self._stop_event.is_set():
            # 线程的执行逻辑
            pass

# 创建并启动线程
thread = MyThread()
thread.start()

# 停止线程
thread.stop()

上記の例では、MyThreadクラスはthreading.Threadクラスを継承し、スレッドの実行ロジックとしてrunメソッドをオーバーライドしています。runメソッドでは、_stop_eventフラグの状態をチェックして、タスクの続行を判断しています。

stopメソッドを呼び出すことで、_stop_eventフラグを設定してスレッドの実行を停止できます。

bannerAds