0
votes

I am implementing thread with callback in Python. I have problem don't know how to pass the arguments to thread job.

What I have done:

import time
import threading


class BaseThread(threading.Thread):
    def __init__(self, callback=None, callback_args=None, *args, **kwargs):
        target = kwargs.pop('target')
        super(BaseThread, self).__init__(target=self.target_with_callback, *args, **kwargs)
        self.callback = callback
        self.method = target
        self.callback_args = callback_args

    def target_with_callback(self):
        self.method()
        if self.callback is not None:
            self.callback(*self.callback_args)


def my_thread_job(param1, param2):
    # do any things here
    print "{} {}".format(param1, param2)
    print "thread start successfully and sleep for 5 seconds"
    time.sleep(5)
    print "thread ended successfully!"


def cb(param1, param2):
    # this is run after your thread end
    print "callback function called"
    print "{} {}".format(param1, param2)


# example using BaseThread with callback
thread = BaseThread(
    name='test',
    target=my_thread_job,
    args=("test","callback"),
    callback=cb,
    callback_args=("hello", "world")
)

thread.start()

I got error

Traceback (most recent call last): File "/usr/lib64/python2.7/threading.py", line 804, in __bootstrap_inner self.run() File "/usr/lib64/python2.7/threading.py", line 757, in run self.__target(*self.__args, **self.__kwargs) TypeError: target_with_callback() takes exactly 1 argument (5 given)

Any suggestion is appreciated.

1

1 Answers

0
votes

Original GitHub Code
This will allow you to pass an initial parameters into the thread.

import time
import threading


class BaseThread(threading.Thread):
    def __init__(self, callback=None, callback_args=None, *args, **kwargs):
        target = kwargs.pop('target')
        target_args = kwargs.pop('target_args')
        super(BaseThread, self).__init__(target=self.target_with_callback, *args, **kwargs)
        self.callback = callback
        self.method = target
        self.method_args = target_args
        self.callback_args = callback_args

    def target_with_callback(self):
        self.method(*self.method_args)
        if self.callback is not None:
            self.callback(*self.callback_args)


def my_thread_job(param1, param2):
    # do any things here
    print "{} {}".format(param1, param2)
    print "thread start successfully and sleep for 5 seconds"
    time.sleep(5)
    print "thread ended successfully!"


def cb(param1, param2):
    # this is run after your thread end
    print "callback function called"
    print "{} {}".format(param1, param2)


# example using BaseThread with callback
thread = BaseThread(
    name='test',
    target=my_thread_job,
    target_args=("threadJobArg1","threadJobArg2"),
    callback=cb,
    callback_args=("hello", "world")
)

thread.start()