python - 覆盖python threading.Thread.run()

标签 python multithreading

鉴于 Python documentation对于 Thread.run():

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

我已经构建了以下代码:

class DestinationThread(threading.Thread):
    def run(self, name, config):
        print 'In thread'

thread = DestinationThread(args = (destination_name, destination_config))
thread.start()

但是当我执行它时,我收到以下错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner
    self.run()
TypeError: run() takes exactly 3 arguments (1 given)

我似乎遗漏了一些明显的东西,但我看到的各种例子都适用于这种方法。最终,我试图将字符串和字典传递到线程中,如果构造函数不是正确的方法,而是在启动线程之前创建一个新函数来设置值,我对此持开放态度。

关于如何最好地完成此任务的任何建议?

最佳答案

你真的不需要子类化 Thread。 API 支持这一点的唯一原因是为了让来自 Java 的人更舒服,这是做到这一点的唯一方法。

我们推荐您使用的模式是将方法传递给 Thread 构造函数,然后调用 .start()

 def myfunc(arg1, arg2):
     print 'In thread'
     print 'args are', arg1, arg2

 thread = Thread(target=myfunc, args=(destination_name, destination_config))
 thread.start()

关于python - 覆盖python threading.Thread.run(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/660961/

相关文章:

python - 我可以像在 hgrc 文件中配置一些扩展一样配置 mercurial hooks 吗?

python - 我正在尝试使用 selenium webdriver 从 Instagram 中抓取姓名?

c# - 获取唯一的线程 ID

c++ - 接收大量 (r) UDP 流量时 CPU 负载高 (Windows)

Java何时启动新线程?

python - Tensorflow:张量的单个元素连接期间出现 ZeroDivisionError

python - 一个 Pandas 数据帧在另一个数据帧中的查找值

java - Java中线程的一致性

c++ - Node JS native 模块 : Can You Run C/C++ Methods In A Separate Libuv/NodeJS Style Process?

python - 从 DataFrame 中的标签获取列号