2014-05-09 3 views
0

스레드 또는 데몬 스레드를 닫거나 종료하려면 어떻게해야합니까? 신청서에 다음과 같은 내용이 있습니다.종료 데몬 스레드

th = ThreadClass(param) 
th.daemon = True 

if option == 'yes': 
    th.start() 
elif option == 'no': 
    # Close the daemon thread 

응용 프로그램을 어떻게 종료합니까?

+1

난 당신이 무슨 뜻인지 모르겠어요. 당신이 가지고있는 if 문의'elif' 브랜치에서, 쓰래드는 결코 시작되지 않았을 것이므로, 그것을 닫을 필요는 없습니다. – Alec

+0

@alecb하지만 처음으로 응용 프로그램을 실행할 때'option'을 값 "yes"로 가정 해 봅시다. 그리고 두 번째로 실행할 때, 나는 옵션을 no로 설정했다. – gspt

+0

스레드가 데몬 스레드 인 경우,'sys.exit (0)'은 스레드를 닫게합니다. 최종 데몬이 아닌 스레드가 종료되면 모든 데몬 스레드가 중지되어야합니다 (_should_). –

답변

0

"지금 죽으십시오"플래그를 사용하여 응용 프로그램을 종료하십시오. 부모 (또는 누군가)가 플래그를 설정하면, 그것을보고있는 모든 스레드가 종료됩니다.

예 :

import time 
from threading import * 

class WorkerThread(Thread): 
    def __init__(self, die_flag, *args, **kw): 
     super(WorkerThread,self).__init__(*args, **kw) 
     self.die_flag = die_flag 

    def run(self): 
     for num in range(3): 
      if self.die_flag.is_set(): 
       print "{}: bye".format(
        current_thread().name 
        ) 
       return 
      print "{}: num={}".format(
       current_thread().name, num, 
       ) 
      time.sleep(1) 

flag = Event() 

WorkerThread(name='whiskey', die_flag=flag).start() 
time.sleep(2) 

print '\nTELL WORKERS TO DIE' 
flag.set() 

print '\nWAITING FOR WORKERS' 
for thread in enumerate(): 
    if thread != current_thread(): 
     print thread.name, 
     thread.join() 
    print