I am trying to gently terminate a running thread in Python by calling stopThread
on the object worker
running in another thread.
However doing so is giving me the error:
AttributeError: 'Thread' object has no attribute 'stopThread'
How can we fix this issue?
import threading
import time
class Worker(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.stopRequest = threading.Event()
def doSomething(self):
while True:
if not self.stopRequest.isSet():
print 'Doing something'
time.sleep(5)
def stopThread(self):
self.stopRequest.set()
def startWorker():
worker = Worker()
worker.doSomething()
# Start thread
t = threading.Thread(target=startWorker)
t.start()
# Stop thread
t.stopThread()