LoginSignup
1
1

More than 1 year has passed since last update.

Python windowsのcmd、powershellでctrl cでスレッド、プロセスが止まらない時の対処法

Last updated at Posted at 2022-03-05

結論

メインスレッド以外をデーモン化する

スレッドのデーモン化とは

デーモンスレッドは他の非デーモンスレッドが終了と同時に強制的に終了するスレッドのこと

また、子スレッドは親スレッドのデーモンの値を継承する
つまり、デーモンスレッドによって開かれた子スレッドは引き続きデーモンスレッド

やり方

以下、極端な例。デーモンスレッド、非デーモンスレッドの順にスレッドを実行させればよい

import threading
from multiprocessing import Process
import time


def task(num: int):
    while True:
        time.sleep(1)
        print(f'task{num}')


def main():
    """ctrl c を受け取るためのスレッド"""
    while True:
        try:
            # スリープ入れないとcpuコアがフル稼働するので注意
            time.sleep(24 * 60 * 60 * 1000)
            
        except KeyboardInterrupt:
            break


def sub():
    threads = []
    # マルチプロセスも同様にして対処可能
    # procs = []
    for i in range(5):
        th = threading.Thread(target=task, args=(i,), daemon=True)
        # proc = Process(target=task, args=(i,), daemon=True)
        # proc.start()
        # procs.append(proc)
        th.start()
        threads.append(th)


sub()
main()
1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1