Djangoであるボタンを押すと内部にスレッドを持つ子スレッドを実行させます。
実行して10秒後に停止処理をいれたとき、
子スレッドが停止しているのにも関わらず孫スレッドが最後まで処理を継続してしまいます。
単体で実行したら想定通り子スレッドが停止したら孫スレッドも停止します。
Djangoでも同じような挙動にするにはどうすればいいでしょうか?
##sample_thread.pyを単体で実行した場合のログ
console
1MainThread: ThreadTwo実行 2ThreadTwo: BotClass実行 3ThreadThree: 0 4ThreadFour: 0 5ThreadThree: 1 6ThreadFour: 1 7ThreadThree: 2 8ThreadThree: 3 9ThreadFour: 2 10 11Process finished with exit code 0
djangoでview経由で実行した場合のログ
console
1Thread-1: ThreadTwo実行 2ThreadTwo: BotClass実行 3ThreadThree: 0 4ThreadFour: 0 5ThreadThree: 1 6ThreadThree: 2 7ThreadFour: 1 8ThreadThree: 3 9ThreadFour: 2 10Dummy-4: ThreadTwo終了 11ThreadThree: 4 12[20/Dec/2016 16:21:40] "GET /sample/ HTTP/1.1" 200 6 13ThreadFour: 3 14ThreadFour: 4 15ThreadFour: BotClass終了
views.py
python
1def sample(request): 2 th2 = ThreadTwo(name='ThreadTwo') 3 th2.start() 4 time.sleep(10) 5 th2.stop() 6 return HttpResponse('sample')
sample_thread.py
python
1import threading 2import time 3 4 5class ThreadTwo(threading.Thread): 6 def __init__(self, name): 7 super(ThreadTwo, self).__init__(name=name) 8 print(threading.currentThread().getName() + ': ThreadTwo実行') 9 self.botclass = BotClass() 10 11 def __del__(self): 12 print(threading.currentThread().getName() + ': ThreadTwo終了') 13 14 def run(self): 15 print(threading.currentThread().getName() + ': BotClass実行') 16 self.botclass.listen() 17 18 def stop(self): 19 self.botclass.listening = False 20 21 22class BotClass: 23 def __init__(self): 24 self.listening = True 25 26 def __del__(self): 27 print(threading.currentThread().getName() + ': BotClass終了') 28 29 def listen(self): 30 th3 = threading.Thread(target=self._thread_three, name='ThreadThree') 31 th3.setDaemon(True) 32 th3.start() 33 th4 = threading.Thread(target=self._thread_four, name='ThreadFour') 34 th4.setDaemon(True) 35 th4.start() 36 while self.listening: 37 # TODO 何かしらの待ち受け処理 38 pass 39 40 def _thread_three(self): 41 for i in range(5): 42 time.sleep(2) 43 print(threading.currentThread().getName() + ': ' + str(i)) 44 45 def _thread_four(self): 46 for i in range(5): 47 time.sleep(3) 48 print(threading.currentThread().getName() + ': ' + str(i)) 49 50 51if __name__ == '__main__': 52 th2 = ThreadTwo(name='ThreadTwo') 53 th2.start() 54 time.sleep(10) 55 th2.stop()
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/01/06 00:10