LoginSignup
0
0

More than 1 year has passed since last update.

【Python Threading】time.sleepが邪魔してスレッドを終了出来ない方へ

Posted at

threadingはフラグ等をチェックせず外部から強制終了させるといったことが出来ないらしいので、ストップフラグを関数に持たせ正常に終了させてあげる必要があります
ですがtime.sleepが文中に存在していると指定した時間が経過するまで次のステップに移行する事が出来ません。なのでストップフラグのチェックが出来なくなり稼働中のスレッドを即座に終了出来ないという訳です

てな訳で

time.sleep内にストップフラグのチェックを入れる

無論Python標準のtime.sleepにそんなオーバーロードは無いので、time.sleepのロジック部分を拝借してストップフラグの部分をぶち込む感じになります
https://github.com/biosbits/bits/blob/master/python/time.py

import threading
import time

threads = []
flag = False

def fun(num=0):
    t = threading.currentThread()
    while getattr(t, "do_run", True):
        print(f"{num+1} flag's:{flag}")
        #sleep
        start = time.time()
        while time.time() - start < 1:
            if not getattr(t, "do_run", True):
                break

def main():
    threads = [threading.Thread(target=fun, args=(i,)) for i in range(0,5)]

    for i in threads:
        i.start()

    #3秒後にスレッドを強制的に落とす
    time.sleep(3)
    for i in threads:
        i.do_run = False
        i.join()
        print("breaked!")

if __name__=="__main__":
    main()

おわりです

0
0
0

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
0
0