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
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.
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:
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.
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.
You are executing foo()
on the main thread by calling t1.run()
. You should call t1.start()
instead.
You have two definitions of foo()
- doesn't matter, but shouldn't be there.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With