当进程是守护进程时,python 的多处理模块的 join()

标签 python multithreading multiprocessing

我很困惑为什么下面的代码块会这样工作。当进程是守护进程且不调用 join() 时与调用 join() 时。当它不调用 join() 时,看起来主进程终止,并且守护进程在主进程终止后都终止:

from multiprocessing import Process
import os

def info(title):
    print(title)
    print('module name:', __name__)
    if hasattr(os, 'getppid'):  # only available on Unix
        print('parent process:', os.getppid())
    print('process id:', os.getpid())

def f(name):
    info('function f')
    print('hello', name)

if __name__ == '__main__':
    info('main line')
    p = Process(target=f, args=('bob',))
    p.daemon = True
    p.start()
    #p.join()

输出:

main line
module name: __main__
parent process: 290
process id: 4793

join() 被调用:

from multiprocessing import Process
import os

def info(title):
    print(title)
    print('module name:', __name__)
    if hasattr(os, 'getppid'):  # only available on Unix
        print('parent process:', os.getppid())
    print('process id:', os.getpid())

def f(name):
    info('function f')
    print('hello', name)

if __name__ == '__main__':
    info('main line')
    p = Process(target=f, args=('bob',))
    p.daemon = True
    p.start()
    p.join()

输出:

main line
module name: __main__
parent process: 290
process id: 4807
function f
module name: __main__
parent process: 4807
process id: 4808
hello bob

最佳答案

是的,你说得对。当主进程终止时,守护进程也将终止。 此页面将为您提供更多详细信息:Why is a Python multiprocessing daemon process not printing to standard output?

关于当进程是守护进程时,python 的多处理模块的 join(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51237129/

相关文章:

python - 将 ReportLab 中的单个段落对齐并居中到一页文档中

python - 没有参数/可迭代的函数的多处理池?

c - 多线程 pthread 错误

c - Socket多线程实现C

Java死锁代码解释

python - python multiprocessing 出现奇怪的进程克隆

Python 多进程池与进程

python - 自动打印下载的文件

python - VirtualBox下Ubuntu如何正确打开8888端口?

python - 如何更改 matplotlib matshow 中矩阵某些元素的颜色?