Reputation: 131
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
Upvotes: 9
Views: 21075
Reputation: 6424
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
Upvotes: 5
Reputation: 11
In addition to the answers given ...
The variable 'run' is a global variable.
When you modify it within another function, e.g. 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()
Upvotes: 1
Reputation: 42795
You don't start a thread by calling run()
, you start it by calling start()
.
Fixing that made it work for me.
Upvotes: 4