2016-06-01 11 views
2

Timerオブジェクトを使用してスレッドを開始しました。さて、私はこのスレッドを停止したいが、できない。 cancel()を使用しましたが、動作しません。どうしてか分かりません。このスレッドを殺すにはどうすればいいですか?

import threading 
import time 
import sys as system 
def Nop(): 
    print("do nothing") 
    return 0 
def function(): 
    try: 
     while True: 
      print("hello world ") 
      time.sleep(2) 
    except KeyboardInterrupt: 
      print("Good job!! exception catched") 
t = threading.Timer(10, function) 
t.start() 
print(t.getName) 
counter = 0 
while True: 
    try: 
     time.sleep(1) 
     Nop() 
     counter = counter +1 
     print(counter) 
     if counter == 20: 
      print(t.getName) 
      t.cancel() 
      counter = 0 
      break 
     if t.is_alive() == False: 
      print("The Timer thread is dead...") 
    except KeyboardInterrupt: 
     print("End of program") 
     t.cancel() 
     system.exit(0) 
    except: 
     print("something wrong happens...") 
if t.is_alive() == True: 
    print("timer is alive...") 
    print(t.getName) 
    t.cancel() 
print("final") 
system.exit(0) 

スレッドは、カウンタが20に等しいときに停止する必要がありますが、まだ生きています。私がwhileループから外れているときは、別のチェックがあります。タイマーは生きている、同じスレッドです、私はキャンセルしようとしますが、動作しません。

do nothing 
17 
hello world 
do nothing 
18 
do nothing 
19 
hello world do nothing 

20 
<bound method _Timer.getName of <_Timer(Thread-6, started daemon 9916)>> 
timer is alive... 
<bound method _Timer.getName of <_Timer(Thread-6, started daemon 9916)>> 
final 
To exit: use 'exit', 'quit', or Ctrl-D. 
An exception has occurred, use %tb to see the full traceback. 

SystemExit: 0 

hello world 
hello world 
hello world 
hello world 

答えて

3

ここでの問題は、the documentationをよく読んで解決できます。タイマースレッドのcancelメソッドは "タイマーがまだ待機中の場合にのみ動作します。"

t.cancelに電話すると、タイマーが起動し、関連付けられている機能が実行されているため、実際にはほとんどの時間がスリープ状態になっていても「待機段階」にはなりません。待機時には、タイマーが起動すると終了します。

さらに一般的には、severalSO answersが既に要約されているため、アクティブな協力なしにスレッドを強制終了する方法はありません。

cancelを使用するのではなく、functionがループ(したがってスレッド全体)を終了するかどうかを判断するフラグを設定する必要があります。

+0

はい、あなたは絶対に正しいです。私はループを止めるために関数にフラグを設定しています。ありがとう –

+0

あなたはそれを釘付けにうれしいです。私はあなたがこの答えを受け入れたものとしてマークしていただければ幸いです。 – holdenweb

関連する問題