退出守护线程
我该如何关闭或退出一个线程或守护线程呢?在我的应用程序中,有这样的代码:
th = ThreadClass(param)
th.daemon = True
if option == 'yes':
th.start()
elif option == 'no':
# Close the daemon thread
我该如何退出这个应用程序呢?
1 个回答
1
通过设置一个“立即退出”的标志来关闭应用程序。当父进程(或者其他任何人)设置了这个标志后,所有监视这个标志的线程都会退出。
示例:
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