Python:如何将参数传递给线程作业(回调)

问题描述 投票:0回答:1

我在Python中使用回调实现线程。我有问题不知道如何将参数传递给线程作业。

我做了什么:

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

我收到了错误

回溯(最近一次调用最后一次):文件“/usr/lib64/python2.7/threading.py”,第804行,在__bootstrap_inner self.run()文件“/usr/lib64/python2.7/threading.py”中,第757行,在run self .__ target(* self .__ args,** self .__ kwargs)TypeError:target_with_callback()只取1个参数(给定5个)

任何建议表示赞赏。

multithreading python-2.7 callback
1个回答
0
投票

Original GitHub Code 这将允许您将初始参数传递给线程。

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()
© www.soinside.com 2019 - 2024. All rights reserved.