Ziq*_*Liu 5 python multiprocessing
这是一个例子:
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')
Run Code Online (Sandbox Code Playgroud)
我希望主进程在启动子进程后立即终止。但是在打印出“完成”之后,终端仍在等待...。是否有任何方法可以使主进程在打印出“完成”之后立即退出,而不是等待子进程?我在这里很困惑,因为我没有打电话p.join()
如果存在非守护进程, Python 不会结束。
通过daemon在start()调用前设置属性,您可以使进程成为守护进程。
p = Process(target=func)
p.daemon = True # <-----
p.start()
print('done')
Run Code Online (Sandbox Code Playgroud)
注意:不会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')
Run Code Online (Sandbox Code Playgroud)
在@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
Run Code Online (Sandbox Code Playgroud)
用法(从文档字符串复制):
import time
@detachify
def f(message):
time.sleep(5)
print(message)
f('Async and detached!!!')
Run Code Online (Sandbox Code Playgroud)
或者如果你喜欢,
def f(message):
time.sleep(5)
print(message)
detachify(f)('Async and detached!!!')
Run Code Online (Sandbox Code Playgroud)