我很困惑为什么下面的代码块以这种方式工作。当进程是守护程序并且不调用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
答案 0 :(得分:1)
是的,您是对的。当主进程终止时,守护进程也将终止。 该页面将为您提供更多详细信息:Why is a Python multiprocessing daemon process not printing to standard output?