重写python threading.Thread.run() [英] Overriding python threading.Thread.run()

查看:711
本文介绍了重写python threading.Thread.run()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Thread.run()提供 Python文档:

您可以在子类中重写此方法.标准的run()方法调用传递到对象构造函数的可调用对象作为目标参数(如果有),并分别从args和kwargs参数中获取顺序参数和关键字参数.

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()

但是当我执行它时,出现以下错误:

But when I execute it, I receive the following error:

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)

似乎我遗漏了一些明显的东西,但是我看到的各种示例都适用于这种方法.最终,我尝试将字符串和字典传递给线程,如果构造方法不是正确的方法,而是在启动线程之前创建一个新函数来设置值,那我很乐意.

It seems I am missing something obvious, but the various examples I have seen work with this methodology. Ultimately I am trying to just pass the string and dictionary into the thread, if the Constructor is not the right way, but rather to make a new function to set the values prior to starting the thread, I am open to that.

关于如何最好地做到这一点的任何建议?

Any suggestions on how to best accomplish this?

推荐答案

您确实不需要为Thread子类化. API支持此功能的唯一原因是使Java使用者感到更舒服,而这是理智地做到这一点的唯一方法.

You really don't need to subclass Thread. The only reason the API supports this is to make it more comfortable for people coming from Java where that's the only way to do it sanely.

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

The pattern that we recommend you use is to pass a method to the Thread constructor, and just call .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 threading.Thread.run()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆