为什么进程没有终止?

时间:2020-05-05 22:33:12

标签: python multithreading

我是多线程新手。在阅读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")

1 个答案:

答案 0 :(得分:1)

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

我建议阅读threading模块的文档,以详细了解我在说什么。

相关问题