Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法在线程中运行的对象中调用函数_Python_Multithreading_Python 2.7 - Fatal编程技术网

Python 无法在线程中运行的对象中调用函数

Python 无法在线程中运行的对象中调用函数,python,multithreading,python-2.7,Python,Multithreading,Python 2.7,我试图通过在另一个线程中运行的对象worker上调用stopThread来温和地终止Python中正在运行的线程 然而,这样做给了我一个错误: AttributeError:'Thread'对象没有属性'stopThread' 我们如何解决这个问题 import threading import time class Worker(threading.Thread): def __init__(self): threading.Thread.__init__(self

我试图通过在另一个线程中运行的对象
worker
上调用
stopThread
来温和地终止Python中正在运行的线程

然而,这样做给了我一个错误:

AttributeError:'Thread'对象没有属性'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()
您有以下错误:

AttributeError:'Thread'对象没有属性'stopThread'
^^^^^^^^^^^^^^
因为

t = threading.Thread(target=startWorker)
..而不是您想要的
工作者
对象

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



或者,您想说:
worker.stopThread()
startWorker()
内部,而不是
t.stopThread()
外部?

有用的线程终止讨论:您没有像您可能认为的那样创建
worker
子类的实例。请参阅示例。我更新了问题中的代码,以更好地反映我正在尝试做的事情。我不熟悉Python中的线程。基本上,试图创建一个对象
Worker
,其中其所有代码都将在不同的线程中运行,运行
doSomething
方法,然后终止线程。我的代码试图让函数
startWorker
在新线程中运行我读取了您的代码。你实际上混淆了很多事情。1)
Worker
类的行为应该像线程一样吗?或者它应该是非线程的,并且做一些工作?如果是后者,那么从
线程
继承
工作者
类就没有意义了。如果是前一个,你应该说:
t=Worker(…)
,就像我回答的第一部分一样。2) 您正在设置
threading.Event
,但从未使用它。应该有一个循环或其他东西来检查这个对象。这让我觉得可能是有意让Worker线程化。看看这个答案:很抱歉给你带来困惑。使用循环和
threading.Event()
再次更新了代码,我在这里试图实现的是在一个单独的线程中异步运行
Worker.doSomething()
,这样主线程仍然可以执行其他任务,stried
t=Worker(target=startWorker)
,但它给出了一个错误
TypeError:\uuu init\uuuuuuuu()获取了意外的关键字参数“target”