Search code examples
pythonmultithreadingpass-by-referencepass-by-value

Python: threading.Thread, are values passed by value or reference?


I'm passing the value i to th = threading.Thread(target=func, args=(i,)) and start the thread immediately by th.start(). Because this is executed inside a loop with changing index i, I'm wondering if i inside the thread retaines its value from the time the thread has been created, or if the thread is working on the reference of i. In the latter case the value wouldn't necessarily be the sames as it was at creation of th. Are values passed by reference or value?


Solution

  • I would say, passing mutable objects to functions is calling by reference.

    You are not alone in wanting to say that, but thinking that way limits your ability to communicate with others about how Python programs actually work.

    Consider the following Python fragment:

    a = [1, 2, 3]
    b = a
    foobar(a)
    if not b is a:
        print('Impossible!')
    

    If Python was a "pass-by-reference" programming language, then the foobar(a) call could cause this program to print Impossible! by changing local variable a to refer to some different object.

    But, Python does not do pass-by-reference. It only does pass-by-value, and that means there is no definition of foobar that could make the fragment execute the print call. The foobar function can mutate the object to which local variable a refers, but it has no ability to modify a itself.

    See https://en.wikipedia.org/wiki/Evaluation_strategy