os.fork和multiprocessing.Process之间的行为差异 [英] Difference in behavior between os.fork and multiprocessing.Process
问题描述
我有此代码:
import os
pid = os.fork()
if pid == 0:
os.environ['HOME'] = "rep1"
external_function()
else:
os.environ['HOME'] = "rep2"
external_function()
和此代码:
from multiprocessing import Process, Pipe
def f(conn):
os.environ['HOME'] = "rep1"
external_function()
conn.send(some_data)
conn.close()
if __name__ == '__main__':
os.environ['HOME'] = "rep2"
external_function()
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p.start()
print parent_conn.recv()
p.join()
external_function
通过在环境变量HOME
的目录中创建必要的子目录来初始化外部程序.此功能在每个过程中仅执行一次.
The external_function
initializes an external programs by creating the necessary sub-directories in the directory found in the environment variable HOME
. This function does this work only once in each process.
在第一个使用os.fork()
的示例中,目录按预期方式创建.但是,使用第二个示例使用multiprocessing
时,仅创建rep2
中的目录.
With the first example, which uses os.fork()
, the directories are created as expected. But with second example, which uses multiprocessing
, only the directories in rep2
get created.
第二个示例为什么不同时在rep1
和rep2
中创建目录?
Why isn't the second example creating directories in both rep1
and rep2
?
推荐答案
The answer you are looking for is in detail addressed here. There is also an explanation of differences between different OS.
一个大问题是fork
系统调用在Windows上不存在.因此,在运行Windows操作系统时,不能使用此方法. multiprocessing
是用于执行部分当前正在运行程序的高级接口.因此,它(与分叉一样)创建您的进程当前状态的副本.也就是说,它可以为您分担程序的开销.
One big issue is that the fork
system call does not exist on Windows. Therefore, when running a Windows OS you cannot use this method. multiprocessing
is a higher-level interface to execute a part of the currently running program. Therefore, it - as forking does - creates a copy of your process current state. That is to say, it takes care of the forking of your program for you.
因此,如果可以的话,您可以考虑fork()
是分叉程序的较低级接口,而multiprocessing
库是分叉程序的较高级接口.
Therefore, if available you could consider fork()
a lower-level interface to forking a program, and the multiprocessing
library to be a higher-level interface to forking.
希望这会有所帮助.
这篇关于os.fork和multiprocessing.Process之间的行为差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!