下面是一个例子:
from multiprocessing import Process
import time
def func():
print('sub process is running')
time.sleep(5)
print('sub process finished')
if __name__ == '__main__':
p = Process(target=func)
p.start()
print('done')
我期望的是主进程将在启动子进程后立即终止。但是打印出"完成"后,终端仍在等待......有没有办法做到这一点,以便主进程在打印出"完成"后立即退出,而不是等待子进程? 我在这里很困惑,因为我没有打电话给p.join()
如果存在非守护进程,Python 将不会结束。
通过在调用之前设置daemon
属性start()
,可以使进程守护进程。
p = Process(target=func)
p.daemon = True # <-----
p.start()
print('done')
注意:不会打印sub process finished
消息;因为主进程将在退出时终止子进程。这可能不是您想要的。
你应该做双叉:
import os
import time
from multiprocessing import Process
def func():
if os.fork() != 0: # <--
return # <--
print('sub process is running')
time.sleep(5)
print('sub process finished')
if __name__ == '__main__':
p = Process(target=func)
p.start()
p.join()
print('done')
在@falsetru的出色回答之后,我以装饰器的形式写了一个快速概括。
import os
from multiprocessing import Process
def detachify(func):
"""Decorate a function so that its calls are async in a detached process.
Usage
-----
.. code::
import time
@detachify
def f(message):
time.sleep(5)
print(message)
f('Async and detached!!!')
"""
# create a process fork and run the function
def forkify(*args, **kwargs):
if os.fork() != 0:
return
func(*args, **kwargs)
# wrapper to run the forkified function
def wrapper(*args, **kwargs):
proc = Process(target=lambda: forkify(*args, **kwargs))
proc.start()
proc.join()
return
return wrapper
用法(从文档字符串复制):
import time
@detachify
def f(message):
time.sleep(5)
print(message)
f('Async and detached!!!')
或者如果你愿意,
def f(message):
time.sleep(5)
print(message)
detachify(f)('Async and detached!!!')