Justin T.
Justin T.

Reputation: 149

How do I update a variable passed onto a thread?

I have main class that runs a thread. I would like to pass a variable into that thread and then update it globally. Is this possible?

Main class:

import subThread

param = 'old param'

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


if __name__ == '__main__':
    Main()

Sub thread:

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'

When I run the Main class, the output is still 'old param'.

Upvotes: 0

Views: 198

Answers (1)

Muge
Muge

Reputation: 469

You just changed the self.param, the variable of subThread instance, not the global variable param

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


if __name__ == '__main__':
    Main()

Upvotes: 2

Related Questions