samie
samie

Reputation: 191

How to change global variables when using parallel programing

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 ?

Upvotes: 0

Views: 1282

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207465

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.

Upvotes: 1

Related Questions