Skip to main content
 首页 » 编程设计

Python:无法访问使用多处理更改的内存

2024年10月17日9jillzhang

这是 python 包中的 python 模块:

import multiprocessing as mp 
 
class Test(object): 
    def __init__(self): 
        self.dict = dict() 
 
    def fill_dict(self): 
        self.dict = {'testing': 123} 
        print self.dict 
 
if __name__ == "__main__": 
    tests = [Test() for i in xrange(3)] 
    jobs = [mp.Process(target=test.fill_dict, args=()) for test in tests] 
    for job in jobs: 
        job.start() 
    for job in jobs: 
        job.join() 
 
    print "RESULTS:" 
    for test in tests: 
        print test.dict 

我运行模块,得到的结果如下:

C:\path\to\package>python -m package.path.to.module 
{'testing': 123} 
{'testing': 123} 
{'testing': 123} 
RESULTS: 
{} 
{} 
{} 

从打印输出来看,似乎每个 test.dict 都由 multiprocessing 并行填充。但是,当我尝试恢复结果时,test.dict 似乎是空的。有人可以解释为什么会发生这种情况以及我可以做些什么来恢复非空的 test.dict 吗?

编辑: @Valentin Lorentz、@Moinuddin Quadri、@zstewart

即使我将模块的后半部分更改为

if __name__ == "__main__": 
    test0 = Test() 
    test1 = Test() 
    test2 = Test() 
 
    jobs = list() 
    jobs.append(mp.Process(target=test0.fill_dict, args=())) 
    jobs.append(mp.Process(target=test1.fill_dict, args=())) 
    jobs.append(mp.Process(target=test2.fill_dict, args=())) 
 
    for job in jobs: 
        job.start() 
    for job in jobs: 
        job.join() 
 
    print "RESULTS:" 
    print test0.dict 
    print test1.dict 
    print test2.dict 

我得到了相同的结果。每个进程都完全独立于其他进程(它们不共享内存,也不需要)。因此,当答案谈到在进程之间共享内存时,这是否意味着在主模块和多处理进程之间?

请您参考如下方法:

您不能使用内置类型在线程之间传输数据。您需要使用 multiprocessing.Queue或 mutiprocess.Pipes执行那个。查看: Exchanging objects between processes .

您可以引用:Running multiple asynchronous function and get the returned value of each function .它有关于如何使用 Queue() 而不是 list 的示例。