I am having trouble with stopping a looping thread. I use an event to stop the loop but the output is different than I expected. I wrote the following code
import threading
from time import sleep
class foo(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.stop_event = threading.Event()
def run(self):
while not self.stop_event.is_set():
print('1')
sleep(1)
print('2')
sleep(1)
print('done')
class bar(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.run_thread()
def run_thread(self):
th1 = foo()
th1.start()
sleep(4)
th1.stop_event.set()
prgm = bar()
prgm.run_thread()
Gives me the output:
1
2
1
2
1
done
2
1
2
done
I expected the word 'done' to be printed onces when the while loop ends. But for some reason 'done' is printed twice. Am I using Events wrong or is the thread started multiple times?