【问题标题】:Python : Passing function as parameter and multithreadingPython:将函数作为参数传递和多线程
【发布时间】:2014-07-23 10:10:01
【问题描述】:

我是 python 新手,我不知道为什么“Without_thread”类有效,而不是“With_thread”类。

我的“With_thread”类的目的是在我用函数调用它时启动一个新线程,这样我就可以同时执行任何函数。 (

import threading

class With_thread(threading.Thread):
    def __init__(self, target, *args):
        self._target = target
        self._args = args
        threading.Thread.__init__(self)

    def run(self):
        self._target(*self._args)

“Without_thread”几乎是同一个类,唯一改变的是我不使用线程。

class Without_thread():
    def __init__(self, target, *args):
        self._target = target
        self._args = args

    def foo(self):
        self._target(*self._args)

我用这个测试我的代码:

def some_Func(data, key):
    print("some_Func was called : data=%s; key=%s" % (str(data), str(key)))

f1 = With_thread(some_Func, [1,2], 6)
f1.start()
f1.join() 

f2 = Without_thread(some_Func, [1,2], 6)
f2.foo()

f1 的输出是:

    self._target(*self._args)
TypeError: 'NoneType' object is not callable

f2 的输出是:

some_Func was called : data=[1, 2]; key=6

如果您能帮我解决这个问题,我将不胜感激,非常感谢您抽出宝贵时间!!!

【问题讨论】:

    标签: python multithreading function-parameter


    【解决方案1】:

    怀疑该问题是由您的 _target 和 _args 与 Thread 中定义的相同属性之间的某种冲突引起的。

    您不需要在 With_thread 中定义 __init__()run()。 Thread 类自己的init 允许您传递关键字参数targetargs,其run() 方法将使用在初始化时提供的args 和kwargs 运行目标。

    所以,你可以完全摆脱 With_thread,然后调用:

    f1 = threading.Thread(target=some_Func, args=([1,2], 6))
    

    【讨论】:

    • 我尝试更改传递给线程的参数名称,异常跳转。为了缩小问题范围,如果我打印_target 的类型是'NoneType',它应该是<class 'function'>
    • 好的,我们可以回到那个。我的建议有用吗?如果是这样,为什么要子类化 Thread?
    • 您的解决方案运行良好。我只是问为什么不按 Rotsap 写的那样工作的原因。
    • 好问题,它在 python 2.7/x64 上对我来说很好
    • 在 some_Func 中应该是什么值
    猜你喜欢
    • 2013-10-29
    • 2022-11-25
    • 2016-10-05
    • 1970-01-01
    • 2022-08-05
    • 2016-02-21
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多