Alex Kasapis Alex Kasapis - 1 year ago 92
Python Question

Python: Change variable value from another thread

Why does the value of my_string not change?

I'm running two threads from two different modules, and module 2 accesses the "set_string" of module 1 in order to change the value of "my_string", but when module 1 prints the string, its empty.

First module:

from threading import Thread
import Module2 as M2
import time

my_string = ""

def set_string(string):
global my_string
my_string = string

def mainloop1():
global my_string
while True:
print("Module 1: ", my_string)

if __name__ == '__main__':
thread = Thread(target=M2.mainloop2)

Second module:

import Module1 as M1
import time
import random

def mainloop2():
while True:
string = str(random.randint(0, 100))
print("Module 2: ", string)

gbe gbe
Answer Source

It's because the methods are implemented in different modules and there are no truly global variables in python; the set_string referenced in Module2 is updating the my_string variable in its globals()['M1'] name where-as Module1 is updating the my_string variable stored directly in globals()['my_string'].

Note that if you move your definition of mainloop2 into Module1, update the imports, and the Thread call then you get your expected behavior, indefinite execution order and all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download