我试图通过调用另一个线程中运行的对象stopThread
上的worker
来轻轻终止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()
答案 0 :(得分:0)
您有错误:
AttributeError: 'Thread' object has no attribute 'stopThread'
^^^^^^^^^^^^^^
,因为
t = threading.Thread(target=startWorker)
..而不是您想要的Worker
对象。
可以说:t = Worker(target=startWorker)
?当然,您必须将关键字参数作为附加参数并将其发送给您的超级班Thread
。
或者,您是否希望在worker.stopThread()
内而不是startWorker()
之外说出t.stopThread()
?