来自https://stackoverflow.com/a/53504673/9191338后:
派生对象被克隆,并在每个进程中最终确定每个对象
fork/forkserver对象在主流程中共享和最终确定
事实似乎是这样:
import os
from multiprocessing import Process
import multiprocessing
multiprocessing.set_start_method('fork', force=True)
class Track:
def __init__(self):
print(f'{os.getpid()=} object created in {__name__=}')
def __getstate__(self):
print(f'{os.getpid()=} object pickled in {__name__=}')
return {}
def __setstate__(self, state):
print(f'{os.getpid()=} object unpickled in {__name__=}')
return self
def __del__(self):
print(f'{os.getpid()=} object deleted in {__name__=}')
def f(x):
print(f'{os.getpid()=} function executed in {__name__=}')
if __name__ == '__main__':
x = Track()
for i in range(2):
print(f'{os.getpid()=} Iteration: {i}, Process object created')
p = Process(target=f, args=(x,))
print(f'{os.getpid()=} Iteration: {i}, Process created and started')
p.start()
print(f'{os.getpid()=} Iteration: {i}, Process starts to run functions')
p.join()
输出是:
os.getpid()=30620 object created in __name__='__main__'
os.getpid()=30620 Iteration: 0, Process object created
os.getpid()=30620 Iteration: 0, Process created and started
os.getpid()=30620 Iteration: 0, Process starts to run functions
os.getpid()=30623 function executed in __name__='__main__'
os.getpid()=30620 Iteration: 1, Process object created
os.getpid()=30620 Iteration: 1, Process created and started
os.getpid()=30620 Iteration: 1, Process starts to run functions
os.getpid()=30624 function executed in __name__='__main__'
os.getpid()=30620 object deleted in __name__='__main__'
事实上,该对象仅在主过程中被删除.
我的问题是,这是如何实现的?虽然新流程是从主流程派生出来的,但Forking 之后,新流程本质上是另一个流程,这两个流程如何共享gc信息呢?
此外,gc信息共享是针对每个对象进行,还是仅针对作为子流程参数传递的对象进行?