I have a problem I am trying to solve with and thought I had found out a possible solution. I want to modify a global variable from within a thread. I found multiple sources that stated that this is possible with the "global" keyword but it doesn't seem to work for me (Using a global variable with a thread)
The code I supplied is a simplified representation of my actual problem. I have a global variable that gets set by a thread and read by the main thread in the meantime. I suspected the output to be:
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: 5
Main: 5
Thread: 6
Thread: 7
Thread: 8
Thread: 9
Thread: 10
Main: 10
Thread: 11
but instead i get:
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: 5
Main: 0
Thread: 6
Thread: 7
Thread: 8
Thread: 9
Thread: 10
Main: 0
Thread: 11
It seems like the "global" globalvar of the Thread is different from the globalvar in the Main Thread and i can't figure out why the same approach is working for other people but not in my case. Why does the Main Thread globalvar stay at 0 if the thread should iterate the global variable?
I know global variables are not best practice but i just want to understand why the code is not working as I expect it to.
from multiprocessing import Process
import time
globalvar = 0
def work():
global globalvar
globalvar += 1
print("Thread:", globalvar)
time.sleep(0.1)
def threaded_function():
while True:
work()
def main_work():
global globalvar
trd = Process(target=threaded_function)
trd.start()
while(trd.is_alive()):
print("Main:", globalvar)
time.sleep(0.5)
if globalvar > 100:
print("Main:", "Done")
trd.terminate()
print("Main:", "Error Exit")