Leuko
Leuko

Reputation: 345

Python: Change passed variable in thread and use the new value outside the thread?

sorry if someone asked this before, but I couldn't find a solution for a weird problem, I have at the moment. Like I was reading in a lot of articles, it should be possible to pass a variable to a thread in Python, change it there, and use the new value in the calling thread? But this is not working for me. I have an example code here:

from threading import Thread

def change(val):
    val = False

def start():
    val = True
    t = Thread(target=change, args=(val,))
    t.start()
    t.join()

    print(val) #--> stays True but should be False

start()

If anyone knows what the problem is, I'm very happy for an answer.

Greetings Leuko

Upvotes: 2

Views: 1581

Answers (1)

Mike67
Mike67

Reputation: 11342

In the method, the memory address of value changes, so it is a different object (a local variable).

For your goal, use an object and change an attribute so the object address stays the same.

Try this code

from threading import Thread

def change(val):
    val[0] = False  # list address stays the same, update attribute

def start():
    val = [True] # list object
    t = Thread(target=change, args=(val,))
    t.start()
    t.join()

    print(val[0])  # False

start()

Note the this also applies when not using multi-threading.

Upvotes: 2

Related Questions