【发布时间】:2017-03-01 23:14:07
【问题描述】:
我试图通过在另一个线程中运行的对象 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()
【问题讨论】:
-
有用的线程终止讨论:stackoverflow.com/questions/323972/…
-
您并没有像您想象的那样创建
Worker子类的实例。有关示例,请参阅How to start and stop thread?。
标签: python multithreading python-2.7