0

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")
FabGre
  • 1
  • 1
  • You're using processes, not threads. – bereal Jan 13 '21 at 17:31
  • I am new to this, I though multiprocessing was just a more capable version of threading(?) – FabGre Jan 13 '21 at 17:34
  • No processes and threads are very different. Check out this answer for a better understanding https://stackoverflow.com/a/3044626/1212401 – Chris Doyle Jan 13 '21 at 17:41
  • The problem is, if I use threads I can't terminate the thread from the outside. And I can't rely on the thread shutting itself down, because it is occasionally stuck in a loop, but I cannot change the code of that loop. That's why I was using Multiprocessing – FabGre Jan 13 '21 at 18:04

0 Answers0