Search code examples
pythonmultithreadingfunction-parameter

Python : Passing function as parameter and multithreading


I'm new with python and I can't find why the "Without_thread" class works and not the "With_thread" class.

The purpose of my "With_thread" class is to launch a new thread when I call it with a function so I can execute any function at the same time. (<==This is what I would like to do)

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)

The "Without_thread" is almost the same class, the only thing changing here is that I don't use threads.

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

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

I test my code with this:

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

The output from f1 is:

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

The output from f2 is:

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

I would really appreciate if you can help me with this, and thank you very much for your time!!!


Solution

  • I suspect the issue is caused by some sort of conflict between your _target and _args and the same attributes defined within Thread.

    You don't need to define __init__() or run() in With_thread. The Thread classes own init allows you to pass keyword arguments target and args, and its run() method will run target with args and kwargs provided at intiialisation.

    So, you can get rid of With_thread entirely, and then call:

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