如何将元组值作为arg发送到作为线程启动的函数?

mix*_*mix 2 python multithreading arguments

我有一个类函数,我想作为一个线程启动.该函数将元组值作为参数.该函数工作正常但我的初始设置抛出TypeError.这是一些示例代码:

import threading

class Test:
    def __init__(self):
        t = threading.Thread(target=self.msg, args=(2,1))
        t.start()
        print "started thread"

    # msg takes a tuple as its arg (e.g. tupleval = (0,1))
    def msg(self,tupleval):
        if(tupleval[0] > 1):
            print "yes"
        else:
            print "no"


test = Test()
test.msg((2,2))
test.msg((0,0))
Run Code Online (Sandbox Code Playgroud)

然后输出如下:

started thread
yes
no
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 532, in __bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 484, in run
    self.__target(*self.__args, **self.__kwargs)
TypeError: msg() takes exactly 2 arguments (3 given)
Run Code Online (Sandbox Code Playgroud)

它似乎适用于最后的两个显式调用,但初始设置调用会抛出TypeError.我已经尝试过以各种方式将值打包到元组中,但无法摆脱错误.想法?

Gle*_*ard 5

args将一个参数元组传递给函数.当你说args=(2,1)你没有告诉它msg用一个论点打电话时(2,1); 你告诉它用两个参数调用它,2并且1.

你想要的args=((2,1),).