【问题标题】:Unable to call function in object running in a thread无法调用线程中运行的对象中的函数
【发布时间】: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()

【问题讨论】:

标签: python multithreading python-2.7


【解决方案1】:

你有错误:

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

因为

t = threading.Thread(target=startWorker)

..而不是您想要的 Worker 对象。

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


或者,您是否要说:worker.stopThread()startWorker() 而不是 t.stopThread() 外?

【讨论】:

  • 我更新了问题中的代码,以更好地反映我正在尝试做的事情。我是 Python 线程的新手。基本上试图创建一个对象Worker,其中所有代码将在不同的线程中运行,运行doSomething 方法然后终止线程。
  • 我的代码试图让函数startWorker 在新线程中运行
  • 我读了你的代码。你实际上混淆了各种各样的事情。 1) Worker 类的行为应该像线程吗?或者它应该是非线程的东西并做一些工作?如果是后者,从Thread 继承Worker 类是没有意义的。如果是先验,您应该说:t = Worker(..),就像我回答的第一部分一样。 2)您正在设置threading.Event,但从未使用它。你应该有一个循环或检查这个对象的东西。这让我觉得可能是打算让 Worker 线程化。看看这个答案:stackoverflow.com/a/27261365/227884
  • 很抱歉给您带来了困惑。再次使用循环更新代码并使用threading.Event(),我在这里想要实现的是在单独的线程中异步运行Worker.doSomething(),这样主线程仍然可以做其他事情
  • 试过t = Worker(target=startWorker),但它给出了一个错误TypeError: __init__() got an unexpected keyword argument 'target'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-11
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 2019-02-02
  • 1970-01-01
相关资源
最近更新 更多