如何更新传递给线程的变量?

时间:2016-04-04 05:13:03

标签: python multithreading pass-by-reference python-multithreading

我有一个运行线程的主类。我想将一个变量传递给该线程,然后全局更新它。这可能吗?

主要课程:

import subThread

param = 'old param'

def Main():
    global param
    s = subThread.subThread(param)
    s.start()
    s.join()
    print(param)


if __name__ == '__main__':
    Main()

子线程:

import threading

class subThread(threading.Thread):

    param = ''

    def __init__(self, param):
        threading.Thread.__init__(self)
        self.param = param

    def run(self):
        self.param = 'new param'

当我运行Main类时,输出仍然是旧的param'。

1 个答案:

答案 0 :(得分:2)

您刚刚更改了self.param,即subThread实例的变量,而不是全局变量param

def Main():
    global param
    s = subThread.subThread(param)
    s.start()
    s.join()
    param = s.param
    print(param)


if __name__ == '__main__':
    Main()