我的目标是让子线程在后台运行,而主线程应该启动它们然后退出:
我尝试了以下代码:
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)
但是一旦主线程退出,我认为子线程也会退出,因为我在threading.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()不会是答案,因为主线程会阻塞。
我根本不想让主线程阻塞。
这个问题有解决方案吗?
提前致谢。
答案 0 :(得分:0)
你不能这样做,这不是关于python的问题,而是关于系统的问题。
如果主进程退出,无论子线程还是子进程都会退出。这是由系统控制的,所以你无能为力。
或者您可以改变主意,为什么必须退出主流程?
答案 1 :(得分:0)
您可以将主进程作为守护进程运行并侦听一些变量或类似的东西(您可以尝试使用json) 如果你将关闭主进程所有其他线程等...将被关闭。
答案 2 :(得分:0)
你应该解释为什么你想要这种行为,因为它不应该是必要的,通过使主线程等待join
它变得休眠,而不是真的消耗更多的功率/内存比它不是& #39;那里
但是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)