1
def foo(var, new_value):
    var = new_value

x = 1
multiprocessing.Process(target=foo, args=(x,2))
p.start()
p.join()
print(x)

I would expect the output of the print(x) is 2, but in fact I got 1. How could I assign new values to an existing variable?

2
  • 3
    Your foo() function doesn't change x, because x is fully evaluated before being passed to the function. var receives the value of x in var. You then change var to a different value. var is a local variable, so it goes away when foo() ends. Commented Aug 6, 2018 at 19:06
  • 1
    Adding to @kindall: The important part here is that this has nothing to do with multiprocessing; this wouldn't work if you just did foo(x, 2) with no multiprocessing involved at all. Commented Aug 6, 2018 at 19:28

1 Answer 1

1

You need to use multiprocessing shared values;

import multiprocessing
import ctypes

def foo(var, new_value):
    var.value = new_value

x = multiprocessing.Value(ctypes.c_int, 1)
print(x.value)
p = multiprocessing.Process(target=foo, args=(x,2))
p.start()
p.join()
print(x.value)
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this is changing two things: 1. It uses shared memory so multiprocessing can transfer data from child to a location where the parent can see it. 2. It changes a rebinding of var in foo to an attribute assignment; rebinding can never change the caller's version of an argument, but modifying an attribute will change the caller's value. #2 isn't specific to multiprocessing; it's a general rule of Python.

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.