简体   繁体   中英

how to share global variables across threads in python?

I want to end a loop running in a separate thread using a global variable. but this code does not seem to stop the thread in loop. I expect the program not to print any more '.' after 2 seconds, but it still runs indefinitely.

Am I doing something fundamentally wrong here?

import time
import threading
run = True

def foo():
    while run:
        print '.',

t1 = threading.Thread(target=foo)
t1.run()
time.sleep(2)
run = False
print 'run=False'
while True:
    pass
  1. You are executing foo() on the main thread by calling t1.run() . You should call t1.start() instead.

  2. You have two definitions of foo() - doesn't matter, but shouldn't be there.

  3. You didn't put a sleep() inside the thread loop (in foo()). This is very bad, since it hogs the processor. You should at least put time.sleep(0) (release time slice to other threads) if not make it sleep a little longer.

Here's a working example:

import time
import threading
run = True

def foo():
    while run:
        print '.',
        time.sleep(0)

t1 = threading.Thread(target=foo)
t1.start()
time.sleep(2)
run = False
print 'run=False'
while True:
    pass

You don't start a thread by calling run() , you start it by calling start() . Fixing that made it work for me.

In addition to the answers given...

The variable 'run' is a global variable.

When you modify it within another function, eg within the main() function, you must make reference to the variable being global otherwise it will not be globally modified.

def main():
    global run
    ...
    run = False
    ...

if __name__ == "__main__":
main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM