我正试图通过在另一个线程中运行的对象worker
上调用stopThread
来轻轻地终止正在运行的Python线程。无法调用在线程中运行的对象中的函数
但是这样做是给我的错误:
AttributeError: 'Thread' object has no attribute 'stopThread'
我们怎样才能解决这个问题?
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()
有帮助的线程终止讨论:http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python – DyZ
你没有创建你的'你可能认为你是工作者的子类。请参阅[** _如何启动和停止线程?_ **](http://stackoverflow.com/questions/15729498/how-to-start-and-stop-thread)示例。 – martineau