Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 退出守护进程线程_Python_Multithreading_Daemon - Fatal编程技术网

Python 退出守护进程线程

Python 退出守护进程线程,python,multithreading,daemon,Python,Multithreading,Daemon,如何关闭/退出线程或守护进程线程?我的应用程序中有如下内容: th = ThreadClass(param) th.daemon = True if option == 'yes': th.start() elif option == 'no': # Close the daemon thread 如何退出应用程序?使用“立即死亡”标志退出应用程序。当父级(或任何人)设置该标志时,所有监视该标志的线程都将退出 例如: import time from threading im

如何关闭/退出线程或守护进程线程?我的应用程序中有如下内容:

th = ThreadClass(param)
th.daemon = True

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

如何退出应用程序?

使用“立即死亡”标志退出应用程序。当父级(或任何人)设置该标志时,所有监视该标志的线程都将退出

例如:

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

我不知道你的意思。在if语句的
elif
分支中,线程永远不会启动,因此不需要“关闭”它。@alecb但假设我第一次运行应用程序时,
选项作为值“yes”。第二次运行时,我将
选项设置为“no”。如果该线程是守护进程线程,则
sys.exit(0)
将导致其关闭。当最后一个非守护进程线程退出时,所有守护进程线程都应该停止。@vgo我想您可能会对守护进程线程的功能感到困惑——它们在多次调用python程序或类似的程序时都不是“持久的”。如果所有其他(非守护进程)线程都已完成,则它们只是无法使程序保持活动状态的线程。请再次注意,只有当所有线程都已死亡时,程序才会结束——线程不会从一次执行延续到另一次执行。但是,关闭非守护进程线程的一种方法是使用
th.join()
,它将等待线程的函数返回。