Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 552
user730094 Avatar asked Apr 28 '11 21:04

user730094


People also ask

How to share global variables between files/modules in Python?

Sharing global variables between files/modules in Python#N#link. Even though the global keyword is conventionally only used to access variables from within the same module, there are ways to use it in order to share variables between files. For example, we could take influence from PHP and create something similar to the "superglobals" variables.

How to share information between threads in Python?

Coming back to the examples from the beginning of the article, we can use queues to share information between threads. We can modify the function such that instead of a list as an argument, it accepts a queue from which it will read elements. Then, it will output the results to an output queue:

How to create a global variable inside a function in Python?

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

Why are global variables worst in threads?

Finally, global variables are not worst in threads. They can be in fact more natural. For example, your thread might just be a block of code, say a loop, that needs its own process. The local scope is thus artificially created when you put the loop in a function. A lock should be considered to use, such as threading.Lock.


1 Answers

  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
like image 161
Boaz Yaniv Avatar answered Oct 05 '22 23:10

Boaz Yaniv