gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:16:13 27 4
gpt4 key购买 nike

我很困惑为什么下面的代码块会这样工作。当进程是守护进程且不调用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com