【问题标题】:Why the process is not terminated?为什么进程没有终止?
【发布时间】:2020-05-06 06:47:08
【问题描述】:

我是多线程的新手。在阅读 Mark Lutz 的“Programming Python”时,我停留在这一行

请注意,由于其简单的无限循环,至少有一个 它的线程可能不会在您可能需要使用的 Windows 上的 Ctrl-C 上死掉 任务管理器杀死运行此脚本的 python.exe 进程或 关闭此窗口即可退出

但是根据我对线程的一点了解 当主线程退出时,所有线程都会终止。那么为什么不在这段代码中呢?

# anonymous pipes and threads, not process; this version works on Windows


import os
import time
import threading


def child(pipe_out):
    try:
        zzz = 0
        while True:
            time.sleep(zzz)
            msg = ('Spam %03d\n' % zzz).encode()
            os.write(pipe_out, msg)
            zzz = (zzz + 1) % 5
    except KeyboardInterrupt:
            print("Child exiting")


def parent(pipe_in):
    try:
        while True:
            line = os.read(pipe_in, 32)
            print('Parent %d got [%s] at %s' % (os.getpid(), line, time.time()))
    except KeyboardInterrupt:
        print('Parent Exiting')


pipe_in, pipe_out = os.pipe()
threading.Thread(target=child, args=(pipe_out, )).start()
parent(pipe_in)
print("main thread exiting")

【问题讨论】:

  • "所有线程在主线程退出时终止" 你从哪里得到这个假设?
  • 如果我错了请纠正我
  • 不,我问的是你是否根据你阅读的内容建立了你的假设,但这可能是你问题的答案,他们没有。

标签: python multithreading


【解决方案1】:

当没有更多正在运行的非守护进程线程时,Python 进程将结束。如果您将daemon=True 参数传递给threading.Thread,您会注意到程序中的不同行为。

我建议阅读threading 模块的文档以了解更多关于我在说什么的信息。

【讨论】:

  • 非常感谢。我终于明白了。
猜你喜欢
  • 2016-07-09
  • 2019-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-15
  • 2014-05-15
  • 1970-01-01
  • 2013-02-20
相关资源
最近更新 更多