python : Passing function as parameter and multithreading

标签 python multithreading function-parameter

我是 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

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

最佳答案

怀疑该问题是由 _target 和 _args 以及线程中定义的相同属性之间的某种冲突引起的。

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

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

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

关于 python : Passing function as parameter and multithreading,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24907633/

相关文章:

python - 如何在html文件中加载css文件已经在django中扩展了另一个html文件(base.html)

python - 我想检查输入是否是 python 代码

Python - 难以置信的大矩阵的最佳数据结构

c# - 将pdf页面转换成1000张以上的图片

.net - 创建异步服务的正确模式是什么?

c# - 'await Task.Delay(1000)' 会阻塞任何线程吗?

更改 C 函数中变量的值

c 函数在调用时不打印并跳转到下一个函数

Python 程序没有按预期提示用户

c - 为什么没有参数的函数(与实际函数定义相比)可以编译?