2017-03-01 60 views
0

我正试图通过在另一个线程中运行的对象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() 
+0

有帮助的线程终止讨论:http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python – DyZ

+0

你没有创建你的'你可能认为你是工作者的子类。请参阅[** _如何启动和停止线程?_ **](http://stackoverflow.com/questions/15729498/how-to-start-and-stop-thread)示例。 – martineau

回答

0

你有错误:

AttributeError: 'Thread' object has no attribute 'stopThread' 
       ^^^^^^^^^^^^^^ 

因为

t = threading.Thread(target=startWorker) 

..和并不像你打算一个Worker对象。

可以这样说:t = Worker(target=startWorker)?当然,您必须将关键字参数作为附加参数并将它们发送到您的超类Thread


或者,你有没有想对你说:worker.stopThread()startWorker()代替t.stopThread()之外?

+0

我更新了问题中的代码,以更好地反映我正在尝试做的事情。我是新来的线程在Python中。基本上试图创建一个对象'Worker',其所有的代码将运行在不同的线程中,运行'doSomething'方法,然后终止线程。 – Nyxynyx

+0

我的代码试图让'startWorker'函数在新线程中运行 – Nyxynyx

+0

我读了你的代码。你实际上混淆了各种各样的东西。 1)“Worker”类应该像线程一样行事吗?还是应该是非线程的东西,并做一些工作?如果是后者,从'Thread'继承'Worker'类是没有意义的。如果是先前的话,你应该说:'t = Worker(..)'就像我答案的第一部分一样。 2)你正在设置'threading.Event',但从不使用它。你应该有一个循环或者一些检查这个对象的东西。这让我觉得可能会打算让Worker看起来像线程一样。看看这个答案:http://stackoverflow.com/a/27261365/227884 – SuperSaiyan