When using a class Pup
for creating stoppable threads that are meant to be running in the background until .stop()
is called:
What happens when
pup.join()
is not called afterpup.stop()
? Will the following result in a leak:pup = Pup() pup.start() time.sleep(5) pup.stop() pup2 = Pup() pup2.start() time.sleep(5) pup2.stop() pup3 = Pup() pup3.start() time.sleep(5) pup3.stop()
Must
pup
be a daemonized thread since we are running it in the background?
Main code below is borrowed from this SO answer
import time
import threading
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self, *args, **kwargs):
super(StoppableThread, self).__init__(*args, **kwargs)
self._stopper = threading.Event()
def stop(self):
self._stopper.set()
def stopped(self):
return self._stopper.isSet()
class Pup(StoppableThread):
def __init__(self, i, *args, **kwargs):
super(Pup, self).__init__(*args, **kwargs)
self.i = i
def run(self):
while True:
if self.stopped():
return
print("Hello, world!", i)
time.sleep(1)
for i in range(100):
pup = Pup(i)
pup.start()
time.sleep(5)
pup.stop()