退出守护程序线程

时间:2014-05-09 20:07:37

标签: python multithreading daemon

如何关闭/退出线程或守护程序线程?我的申请表中有这样的内容:

th = ThreadClass(param)
th.daemon = True

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

如何退出申请?

1 个答案:

答案 0 :(得分: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