简体   繁体   English

Python类不会更改类变量

[英]Python class doesn't change class variable

Hi I am writing a simple script with multiple processes. 嗨,我正在编写一个具有多个进程的简单脚本。 Here is class that I am using: 这是我正在使用的课程:

class WorkerProcess(multiprocessing.Process):
    def __init__(self, batch):
        multiprocessing.Process.__init__(self)
        self.batch = batch
        self.data_frame = pd.DataFrame()

    def run(self):
        temp = []
        for item in self.batch:
            temp.append(item)
        self.data_frame = pd.DataFrame(temp, columns=temp[0].keys())
        print('empty: ', self.data_frame.empty) # everything is fine

Later I start processes and join them: 后来我开始流程并加入其中:

    workers = []
    for i in range(max_processes):
        try:
            batch = batches_data.pop()
            workers.append(WorkerProcess(batch))
        except Exception as e:
            pass

    for worker in workers:
        worker.start()

    for worker in workers:
        worker.join()

    for worker in workers:
        print(worker.data_frame) # it is empty

When I print data_frame it is empty even though is was changed in run() function. 当我打印data_frame时,即使在run()函数中更改了它,它也是空的。

What am I missing? 我想念什么?

Processes do not share their memory address space. 进程不共享其内存地址空间。 Thanks to Linux process forking strategy, you usually get the feeling the child process share its memory with the parent but in reality it's a copy. 借助Linux进程分叉策略,您通常会感觉到子进程与父进程共享其内存,但实际上它是一个副本。

This means that changes in the child process will not be reflected in its parent (or in any other process). 这意味着子进程中的更改将不会反映在其父进程(或任何其他进程)中。

The Python multiprocessing library offers several mechanisms to share memory between processes . Python多处理库提供了几种在进程之间共享内存的机制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM