如何在 Python 中退出主线程并使子线程在后台继续



我的目标是让子线程在后台运行,而主线程应该启动它们然后退出:

我尝试了以下代码:

import time
import logging
import threading
logging.basicConfig(filename="threading.log",level=logging.DEBUG)
def worker(count):
for c in range(count,-1,-1):
threadname = threading.currentThread().getName()
threadcount = threading.active_count()
threadnames = threading.enumerate()
logging.debug("Child thread: {} continuing with threadcount {} {} and counter value: {}".format(threadname,threadcount,threadnames,c))
time.sleep(2)
mainthread = threading.currentThread().getName()
print ("Starting main thread:",mainthread)
t1 = threading.Thread(target=worker,args=(10,))
t1.setDaemon(True)
t1.start()
time.sleep(5)
print ("Attempting to close main thread:",mainthread)

但是一旦主线程退出,我认为子线程也会退出,因为我在线程中.log(我从子线程创建(中有此输出

DEBUG:root:Child thread: Thread-1 continuing with threadcount 2 [<_MainThread(MainThread, started 1160)>, <Thread(Thread-1, started daemon 10232)>] and counter value: 10
DEBUG:root:Child thread: Thread-1 continuing with threadcount 2 [<_MainThread(MainThread, started 1160)>, <Thread(Thread-1, started daemon 10232)>] and counter value: 9
DEBUG:root:Child thread: Thread-1 continuing with threadcount 2 [<_MainThread(MainThread, started 1160)>, <Thread(Thread-1, started daemon 10232)>] and counter value: 8

我知道使用 join(( 不会是答案,因为主线程会阻塞。

我根本不希望主线程阻塞。

有解决问题的方法吗?

提前谢谢。

你不能那样做,这不是关于python的问题,而是关于系统的问题。

无论子线程还是子进程,如果主进程退出,都会退出。这是由系统控制的,所以你不能对它做任何事情。

或者你可以改变主意,为什么你必须退出你的主进程?

你可以把主进程作为一个守护进程运行,并侦听一些变量或类似的东西(你可以尝试用json( 如果您将关闭主进程所有其他线程等...将被关闭。

你应该解释为什么你想要这种行为,因为它不应该是必要的,通过让主线程等待它进入休眠join,而不是真正消耗更多的功率/内存比它不存在时更多。
但是,t1.setDaemon(True)是使子线程在主进程停止时停止的原因,注释掉或删除此行,它应该做您想要的。但这也不是好的做法。 例:

import time
import logging
import threading
logging.basicConfig(filename="threading.log",level=logging.DEBUG)
def worker(count):
for c in range(count,-1,-1):
threadname = threading.currentThread().getName()
threadcount = threading.active_count()
threadnames = threading.enumerate()
logging.debug("Child thread: {} continuing with threadcount {} {} and counter value: {}".format(threadname,threadcount,threadnames,c))
time.sleep(2)
mainthread = threading.currentThread().getName()
print ("Starting main thread:",mainthread)
t1 = threading.Thread(target=worker,args=(10,))
#t1.setDaemon(True) # do not set daemon
t1.start()
time.sleep(5)
print ("Attempting to close main thread:",mainthread)

最新更新