我注意到我可以访问子进程中位于子进程函数/目标之外的函数和模块。所以我想知道当我在 python 中创建子进程时它是否会复制当前进程中的所有内容?为什么我可以访问子目标之外的函数和导入的模块?
from multiprocessing import Process, Pipe
def test1():
return "hello"
def simpleChildProcess( childPipe ):
# simpleChildProcess can access test1 function
foo = test1()
childPipe.send( foo )
parentPipe, childPipe = Pipe()
childProcess = Process( target=simpleChildProcess, args=(childPipe,) )
childProcess.start()
print "Pipe Contains: %s" % parentPipe.recv()
在类 Unix 操作系统上,multiprocessing.Process
uses os.fork https://stackoverflow.com/q/33560802/190597产生新的进程。fork
创建一个新进程,该进程是父进程的副本,分叉进程从该点恢复fork
被称为。
由于 Windows 缺乏fork
, multiprocessing.Process
启动一个新的Python进程并导入调用模块。在 Windows 上,调用Process
必须在里面if __name__ == '__main__'
阻止Process
避免每次导入调用模块时都被重复调用。 (即使在 Unix 上,包含以下内容也是一个很好的做法if __name__ == '__main__':
以防止您的代码导致失控的进程生成)。
因此,子进程可以访问调用模块定义的函数和模块到目前为止 where Process
已被调用(对于 Unix 而言)或在导入调用模块之后(对于 Windows 而言)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)