【问题标题】:Daemon thread vs Non Daemon thread in pythonpython中的守护线程与非守护线程
【发布时间】:2020-01-05 15:54:13
【问题描述】:

我有以下代码:

import threading 
from time import sleep

def print_function1():
    while True:
        print("Hi this is function 1\n") 
        sleep(2)

if __name__ == "__main__": 
    # creating thread 
    t1 = threading.Thread(target=print_function1 ) 

    t1.daemon = True

    # starting thread 1 
    t1.start() 

    sleep(10)

    # both threads completely executed 
    print("Done!") 

现在我无法理解如果我设置 t1.daemon True 或 False 会有什么不同,我在蜘蛛 Ipython 控制台中运行代码。

在这两种情况下,程序似乎都没有退出,它一直在打印“嗨,这是函数 1”。 我的假设是主线程完成后守护线程将继续运行,但正常线程将退出。

谁能解释一下。

【问题讨论】:

  • 实际上恰恰相反:当主线程存在时,守护线程不会继续运行。这段代码也适用于我(=当 daemon=True 时程序存在,当 daemon=False 时相反)
  • 但对我来说,这两种情况下都会继续打印。在守护进程的情况下它应该停止打印吗??
  • 是的。你用的是哪个版本的python?
  • 嘿,Tomer,我确实想通了,这是因为将 python 代码运行到 python shell 与从命令行运行 python 文件的行为不同。这是参考答案:stackoverflow.com/questions/21843916/…。感谢您的帮助。

标签: python multithreading daemon


【解决方案1】:

这个问题是因为在将 python 代码运行到 python shell 时,守护进程线程观察到了不同的行为,比如我的例子中的 Spyder 中的 Ipython 与从命令行运行 python 文件(如“python thread_example.py”)。

从命令行运行文件会给出预期的行为。

可以参考这个 stackoverflow 答案:Python daemon thread does not exit when parent thread exits

【讨论】:

    【解决方案2】:

    它使线程在后台运行而不中断主工作,如果为真,或者在假时作为主线程运行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-24
      • 1970-01-01
      • 2011-07-13
      相关资源
      最近更新 更多