0

我有这个代码

class MyTh(threading.Thread):

    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs=None, verbose=None):
        threading.Thread.__init__(self, group=group, target=target, name=name,
                                  verbose=verbose)
        self.args = args
        self.kwargs = kwargs
        return

    def run(self):
        logging.debug('running with %s and %s', self.args, self.kwargs)
        return

def my_func(): 
   print 'Everything OK'

当我这样做时

t1 = MyTh(name='Thread '+ str(i), target=myfunc, args=("test",), kwargs={'a':'A', 'b':'B'})
    t1.start()

我的目标函数根本没有被调用。我怎样才能让我的线程调用目标中给出的默认函数

4

1 回答 1

1

通过覆盖该run()方法,您会弄乱标准run()并且永远不会调用目标。您需要的是不覆盖该方法或像这样覆盖它:

def run(self):
    logging.debug('running with %s and %s', self.args, self.kwargs)
    super(MyTh, self).run()
    return

这样,标准Thread.run也被调用并被target执行。

你也没有传递argskwargs构造Thread函数。你需要有:

threading.Thread.__init__(self, group=group, target=target, name=name,
                              verbose=verbose, args=args, kwargs=kwargs)

为了使它们正确设置。然后你可以改变你my_func的:

def my_func(arg1, a, b):
    print arg1, a, b
    print 'Everything OK'

此外,MyTh' 的构造函数和调用Thread.__init__是不必要的长。这要短得多且可读性强:

def __init__(self, *args, **kwargs):
    threading.Thread.__init__(self, *args, **kwargs)
    self.args = kwargs['args']
    self.kwargs = kwargs['kwargs']

Notice how the args and kwargs which you pass to the constructor are actually accessible as kwargs['args'] and kwargs['kwargs']

于 2013-03-01T08:55:13.727 回答