Does Daemon Thread Exit with Main Thread?

主线程(进程)退出后,主线程创建的守护线程也会退出吗?

通过下面的代码测试:

Demo1: 进程创建普通线程

#!/usr/bin/python3
# FileName: daemonThread.py
# Author: lxw
# Date: 2016-02-25

import threading
import time

def show(num):
    time.sleep(3)
    print("In show(): {0}".format(num))
    with open("/home/lxw/Documents/NOTE", "w") as f:
        f.write("hello")

def main():
    th = threading.Thread(target=show, args=(1,))
    #th.setDaemon(True)
    th.start()
    print("main() over. Program exit!")

if __name__ == ‘__main__‘:
    main()
else:
    print("Being imported as a module.")

运行结果:

lxw Documents$ python3 daemonThread.py
main() over. Program exit!
In show(): 1
lxw Documents$ 

"The entire Python program exits when no alive non-daemon threads are left".

只有当前进程的所有非守护线程 全部结束后,当前进程才能结束。

Demo2: 进程创建守护线程

#!/usr/bin/python3
# FileName: daemonThread.py
# Author: lxw
# Date: 2016-02-25

import threading
import time

def show(num):
    time.sleep(3)
    print("In show(): {0}".format(num))
    with open("/home/lxw/Documents/NOTE", "w") as f:
        f.write("hello")

def main():
    th = threading.Thread(target=show, args=(1,))
    th.setDaemon(True)
    th.start()
    print("main() over. Program exit!")

if __name__ == ‘__main__‘:
    main()
else:
    print("Being imported as a module.")

运行结果:

lxw Documents$ ls
daemonThread.py  NOTE  ThreadPool_Python
lxw Documents$ rm NOTE
lxw Documents$ ls
daemonThread.py  ThreadPool_Python
lxw Documents$ python3 daemonThread.py
main() over. Program exit!
lxw Documents$ ls
daemonThread.py  ThreadPool_Python

从运行结果我们可以看到,当前进程的守护线程 并没有结束,但当前进程仍然可以退出。并且当前进程结束后,该进程的守护线程也会结束,不会继续运行。

也就是说进程退出并不考虑守护线程,只考虑非守护线程。

通过这两段代码的验证,我们可以得出本文标题的答案:进程结束后,该进程的守护线程也会结束,不会继续运行。

Reference:

1. [Java基础] java的守护线程与非守护线程 虽然这篇文章讲的是Java的,但和Python也是通用的。
守护线程并非虚拟机内部可以提供,用户也可以自行的设定守护线程,方法:public final void setDaemon(boolean on) ;但是有几点需要注意:
1). thread.setDaemon(true)必须在thread.start()之前设置,否则会跑出一个 IllegalThreadStateException异常。你不能把正在运行的常规线程设置为守护线程。(备注:这点与守护进程有着明显的区别, 守护进程是创建后,让进程摆脱原会话的控制+让进程摆脱原进程组的控制+让进程摆脱原控制终端的控制;所以说寄托于虚拟机的语言机制跟系统级语言有着本质上面的区别)
2). 在Daemon线程中产生的新线程也是Daemon的。(这一点又是有着本质的区别了:守护进程fork()出来的子进程不再是守护进程,尽管它把父进程的进程相关信息复制过去了,但是子进程的进程的父进程不是init进程,所谓的守护进程本质上说就是“父进程挂掉,init收养,然后 文件0,1,2都是/dev/null,当前目录到/”)

2. 这篇博文的评论

时间: 2024-10-21 09:47:15

Does Daemon Thread Exit with Main Thread?的相关文章

Sub Thread to update main Thread (UI) 2

Sub Thread to update main Thread (UI)  2 Handler.post(somethread); Handler.sendMessage("Msg"); 1 import android.app.Activity; 2 import android.os.Bundle; 3 import android.os.Handler; 4 import android.os.Message; 5 import android.util.Log; 6 impo

Sub Thread to update main Thread (UI)

Sub Thread to update main Thread (UI) main Thread :   A  has Hander.HandleMessage() to process the "Msg" from subthread B; Sub Thread :    B  use  Hander.sendMessage(Msg)  to main Thread A; 1 import java.util.Timer; 2 import java.util.TimerTask;

MFC data forwarding to main thread via PostMessage

MFC data forwarding to main thread via PostMessage          up vote3down votefavorite 3 I have a C++/MFC application I need to restructure. The app used to process most of the data on the main thread, therefore blocking the input, and now I want to c

main thread starting…

执行结果例如以下: main thread starting- Thrad 2 staring- Thrad 2 end- Thrad 4 staring- Thrad 4 end- Thrad 1 staring- Thrad 1 end- Thrad 3 staring- Thrad 3 end- Thrad 5 staring- Thrad 5 end- main thread end- CountDownLatch方式代码例如以下: package com.test.thread; im

jquery.js:8672 Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

html5谷歌流浪器报错:jquery.js:8672 Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/. 解决方法: 所有的a标签加上:javascript:void(0) <a href="

主线程任务太多导致异常退出(The application may be doing too much work on its main thread)

今天花费了一天的时间来解决这个bug. 这种在程序运行期间出现的问题比较棘手,如果再没有规律的话就更难解决. 还好这个bug是由规律的,也就是说在程序执行半个小时左右后就会因为此异常而导致程序退出:那么在网上找了下原因,无非是说一下几点: 1.把业务放在子线程中去完成,然后通过handler来更新界面 2.通过runOnUiThread的方法来实现 再补充一点就是:优化代码,将不需要重复执行的代码执行一次就ok了,特别是需要绘制UI的代码更不能随便放在重复执行的地方 一.bug现场还原 我的程序

Error: CompareBaseObjectsInternal can only be called from the main thread

Posted: 01:39 PM 06-17-2013 hi, we're working on a project where we need to do some calculations on a separate thread. The data we need for the calculations is stored on a scriptable object. We use the scriptable object so that we can serialize the d

Unity3d报告奇怪的错误CompareBaseObjectsInternal can only be called from the main thread.

其中使用了该项目.NET的Async Socket代码.后来不知道什么时候这个奇怪的错误的出现: CompareBaseObjectsInternal can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the con

Service 是否在 main thread 中执行, service 里面是否能执行耗时的操作?

默认情况,如果没有显示的指 service 所运行的进程, Service 和 activity 是运行在当前 app 所在进程的 main thread(UI 主线程)里面.service 里面不能执行耗时的操作(网络请求,拷贝数据库,大文件 )特殊情况 ,可以在清单文件配置 service 执行所在的进程 ,让 service 在另外的进程中执行 <service android:name="com.baidu.location.f" android:enabled=&quo