如何将self和2个参数传递给线程

时间:2019-01-04 21:38:48

标签: python multithreading parameter-passing

我只是试图将self和另外2个参数传递给线程,但是每次都会遇到错误。

我尝试了其他示例,但到目前为止没有任何效果。

class X:
    def start(self):
        newStartupThread = threading.Thread(target=self.launch, args=(t1_stop, 
            self.launchAdditionalParams))
        newStartupThread.name = "ClientLaunchThread%d" % 
            (self.launchAttemptCount+1)
        newStartupThread.daemon = True
        newStartupThread.start()


    def launch(self, test, additionalParams):
        pass

我收到此错误:

TypeError: launch() takes at most 2 arguments (3 given)

**编辑代码以表明它在课程中

2 个答案:

答案 0 :(得分:1)

self的存在出发,我认为这是在一个类中。

import threading


class X:
    def start(self):
        t1_stop = 8
        self.launchAdditionalParams = {}

        newStartupThread = threading.Thread(
            target=self.launch,
            args=(t1_stop, self.launchAdditionalParams),
        )
        newStartupThread.name = "ClientLaunchThread"
        newStartupThread.daemon = True
        newStartupThread.start()

    def launch(self, test, additionalParams):
        print(locals())


x = X()
x.start()

对我来说效果很好,输出

{'additionalParams': {}, 'test': 8, 'self': <__main__.X object at 0x000001442938F438>}

答案 1 :(得分:0)

launch是函数,而不是方法。只有方法需要self参数。只需删除self参数,它应该可以工作:

def launch(test, additionalParams):

如果它在课程中,则必须执行以下两项操作之一:

    在类(someClass.launch(arg1, arg2))的实例上
  • 调用
  • 通过不包含self自变量来使其成为static method