Python 3において、スレッドを終了させる方法はありますか?

PYTHON3 チュートリアル

Python 3におけるスレッドの終了方法

Python 3では、スレッドを終了させる方法として、スレッドを停止させるためのフラグを使用する方法や、スレッドを強制終了させる方法があります。

1. フラグを使用したスレッドの終了

スレッドを終了させるためには、スレッド内で定期的にフラグをチェックし、フラグが立っている場合にスレッドを終了させるようにします。

import threading
import time

# スレッドが終了するかどうかを管理するフラグ
stop_flag = False

def my_thread_function():
    global stop_flag
    while not stop_flag:
        print("Running...")
        time.sleep(1)
    print("Thread stopped.")

# スレッドを作成して開始
my_thread = threading.Thread(target=my_thread_function)
my_thread.start()

# 5秒後にスレッドを終了させる
time.sleep(5)
stop_flag = True

上記の例では、`stop_flag`が`True`になるとスレッドが終了します。

2. スレッドを強制終了する方法

スレッドを強制終了する方法として、`Thread`オブジェクトの`terminate()`メソッドを使用する方法があります。

import threading
import time

def my_thread_function():
    while True:
        print("Running...")
        time.sleep(1)

# スレッドを作成して開始
my_thread = threading.Thread(target=my_thread_function)
my_thread.start()

# 5秒後にスレッドを強制終了
time.sleep(5)
my_thread.terminate()

ただし、`terminate()`メソッドはPythonの標準ライブラリには含まれておらず、スレッドを安全に終了させる方法ではないため、避けることが推奨されています。

3. `threading.Event`を使用したスレッドの終了

もう1つの方法として、`threading.Event`を使用してスレッドの終了を制御する方法があります。

import threading
import time

stop_event = threading.Event()

def my_thread_function():
    while not stop_event.is_set():
        print("Running...")
        time.sleep(1)
    print("Thread stopped.")

# スレッドを作成して開始
my_thread = threading.Thread(target=my_thread_function)
my_thread.start()

# 5秒後にスレッドを終了させる
time.sleep(5)
stop_event.set()

上記の例では、`stop_event`がセットされるとスレッドが終了します。

購読
通知
0 Comments
Inline Feedbacks
View all comments