0

I have a while True loop that needs to be run in the background to update a variable and a function that needs to return that same variable. I tried this as a test:

import threading
downspeed = 0

def updating():
    while True:
        downspeed = downspeed+1

def main():
    while True:
        print(downspeed)


u = threading.Thread(name='background', target=updating)
m = threading.Thread(name='foreground', target=main)

u.start()
m.start()

But it only returns 0

2
  • Every function has its own variable namespace. Commented Jul 26, 2021 at 19:56
  • if you want downspeed to be a global variable, you should put global downspeed at the beginning of the function definition of updating (inside the function). for main, since downspeed is not defined in the function scope, it will use the global scope, but if you set a variable within a function, it will become local unless you use global (and in this case updating should error, I believe) Commented Jul 26, 2021 at 19:57

1 Answer 1

1

Your code is not really a sufficient test. The test ought to include:

  1. Allowing some time for the threads to run to see what they do.
  2. Make the threads sleep, at least for a little time, to allow task switches to occur.

See this code:

import threading
import time

can_run = True
downspeed = 0

def updating():
    global downspeed
    while can_run:
        downspeed = downspeed+1
        time.sleep(0.1)   # Allow taskswitches

def main():
    while can_run:
        print(downspeed)
        time.sleep(1)   # Allow taskswitches


u = threading.Thread(name='background', target=updating)
m = threading.Thread(name='foreground', target=main)

u.start()
m.start()

time.sleep(10)  # Allow time for the threads to do what they want
can_run = False
print('Done')
u.join()
m.join()

There are no problems sharing variables in python because of the GIL. Although this only makes changes atomic.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.