Bigfoot29
Bigfoot29

Reputation: 70

Python multiprocessing: "self."variable not updated in/by other functions?

Looks like I am out of luck here... sorry to ask you folks. :(

I am trying to do the following:

import multiprocessing
import time

class TestClass(multiprocessing.Process):
    def __init__(self):
        super(TestClass, self).__init__()
        print("Initializing the test class...")
        self.VARIABLE = 0

    def run(self):
        while self.VARIABLE < 10:
            print("Sleeping... Variable now: " + str(self.VARIABLE))
            time.sleep(1)

    def setVar(self, VALUE):
        print("Setting new value from " + str(self.VARIABLE) + " to " + str(VALUE) + " ...")
        self.VARIABLE = VALUE


if __name__ == "__main__":
    TESTPROCESS = TestClass()
    TESTPROCESS.start()
    time.sleep(5)
    TESTPROCESS.setVar(5)
    time.sleep(5)
    TESTPROCESS.setVar(10)

However, in the result, it doesn't update the self.VARIABLE in run(), but only in setVar().

c:\Python35\python.exe Test.py
Initializing the test class...
Sleeping... Variable now: 0
Sleeping... Variable now: 0
Sleeping... Variable now: 0
Sleeping... Variable now: 0
Sleeping... Variable now: 0
Setting new value from 0 to 5 ...
Sleeping... Variable now: 0
Sleeping... Variable now: 0
Sleeping... Variable now: 0
Sleeping... Variable now: 0
Sleeping... Variable now: 0
Setting new value from 5 to 10 ...
Sleeping... Variable now: 0
Sleeping... Variable now: 0
[...]

I thought, "self" would indicate, that this are "global" parameters for this class/object?

Even when I modify the run() function to have a "while true: --> break" loop, the same issue still occurs. Where is my thinking error?

Thanks in advance...

Upvotes: 1

Views: 2005

Answers (1)

jwodder
jwodder

Reputation: 57610

TESTPROCESS.start() causes the run() method to be executed in a separate process; that's kind of the entire point. As a result, you do not have one TestClass instance; you have two, and they exist in separate processes. One of these instances is updated by your calls to setVar, and the other (due to being a different object) is not. If you want to be able to communicate between processes, look into pipes and queues.

Upvotes: 2

Related Questions