George Pligor George Pligor - 3 years ago 114
Python Question

Are global variables get replicated in each process when doing multiprocessing in Python?

We have used parallel processing by having some functions being called by

that you will find in this answer:

All of these functions are supposed to have access to a single global variable which they should read.

This global variable is actually an instance of a class. This instance contains a member variable/attribute and all of the processes read and write to it.

However things are not happening like this. The object(class instance) seems to be replicated and that its attributes are independent on each process. So if one process changes the value this is not visible to the variable of the other process.

Is this the expected behavior?

How to overcome it?

Thank you

Answer Source

All children processes will inherit that instance at the moment of forking from the parent process. Any changes made to the instance in the children and in the parent will NOT be seen after the fork.

This is how the processes work in Linux — every process has its own memory, protected from other processes (unless you intentionally shared it). It is not Python-specific.

What you are looking for is called IPC (Inter-Process Communication) in general. There are multiple ways how the processes can communicate with each another. You might want to use pipes or the shared memory.

In Python, read this:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download