スレッドが終了するタイミングについて検証

Pythonでスレッドをしばらく使っていなくて、どういう動きするのだったか忘れてたので、検証したメモを残す。
試した環境は、Ubuntu 14.04、Python 3.5.1。

検証に使ったコード

main.py:

import threading
import os
import sys
import time
import signal


def spam():
    for i in range(5):
        time.sleep(1)
        print("value: {}".format(i))


def main_1():
    t = threading.Thread(target=spam)
    t.start()
    print("Thread: {} started.".format(t.ident))
    sys.exit()


def main_2():
    t = threading.Thread(target=spam)
    t.start()
    print("Thread: {} started.".format(t.ident))
    t.join()  # スレッドの処理が終わるのを待つ
    print("Thread end.")
    sys.exit()


def main_3():
    t = threading.Thread(target=spam)
    t.start()
    print("Thread: {} started.".format(t.ident))
    # 自身のプロセスにSIGKILLを送って強制終了
    os.kill(os.getpid(), signal.SIGKILL)

実行結果

pythonの-cオプションを使って、各検証の関数を実行。

(venv) tokibito@tokibito-MacBookAir:~/sandbox$ python -c "import main;main.main_1()"
Thread: 140258192140032 started.
value: 0
value: 1
value: 2
value: 3
value: 4
(venv) tokibito@tokibito-MacBookAir:~/sandbox$ python -c "import main;main.main_2()"
Thread: 139913801033472 started.
value: 0
value: 1
value: 2
value: 3
value: 4
Thread end.
(venv) tokibito@tokibito-MacBookAir:~/sandbox$ python -c "import main;main.main_3()"
Thread: 140079644133120 started.
強制終了
  • sys.exit()を呼んでも、処理中のスレッドがいると、プロセスは終了しない
  • Thread.join()を呼ぶと、スレッドが終了するまで待つ
  • SIGKILLをプロセスに送ると、スレッドごとプロセスが強制終了される

2018/4/14追記

  • daemon=True を指定してデーモンモードでスレッドを作った場合は、スレッドの終了を待たずに強制終了する。