0

I am using multiprocessing in my code to do somethings parallel. Actually in a simple version of my goal, I want to change some global variables by two different processes in parallel.

But in the end of the code running, the result which is getting from mp.Queue is true but the variables are not changed.

here is a simple version of code:

import multiprocessing as mp

a = 3
b = 5

# define a example function
def f(length, output):
    global a
    global b
    if length==5:
       a = length + a
       output.put(a)
    if length==3:
       b = length + b
       output.put(b)


if __name__ == '__main__':

     # Define an output queue
     output = mp.Queue()    

     # Setup a list of processes that we want to run
     processes = []
     processes.append(mp.Process(target=f, args=(5, output)))
     processes.append(mp.Process(target=f, args=(3, output)))

     # Run processes
     for p in processes:
         p.start()

     # Exit the completed processes
     for p in processes:
         p.join()

     # Get process results from the output queue
     results = [output.get() for p in processes]

     print(results)
     print ("a:",a)
     print ("b:",b)

And the blow is the answers:

[8, 8]
a: 3
b: 5

How can I apply the results of processes to the global variables? or how can I run this code with multiprocessing and get answer like running a simple threat code ?

1 Answer 1

1

When you use Threading, the two (or more) threads are created within the same process and share their memory (globals).

When you use MultiProcessing, a whole new process is created and each one gets its own copy of the memory (globals).

You could look at mutiprocessing Value/Array or Manager to allow pseudo-globals, i.e. shared objects.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this great answer it solved a lot of questions I had. I went through the code with the help of your explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.