xc wang
xc wang

Reputation: 372

In a parent process, how to see child variables that are managed by child processes?

I defined a class Node, which defines a listener service to constantly communicate and update local variables. The listener is started using multiprocessing. The class looks like:

# Pseudo-code
import multiprocessing
class Node(object):
    def __init__(self, x):
        self.variables = x
    def listener(self):
        while(True):
            COMMUNICATE WITH OTHERS     # Pseudo-code
            UPDATE self.variable        # Pseudo-code
            print(self.variable)        # local printer
    def run(self):
        p = multiprocessing.Process(target=self.listener)
        p.start()

In the main process, I created two nodes a = Node(x1), b = Node(x2), and let them run

if __name__ == "__main__":
    x1 = 1       # for example
    x2 = 1000    # for example
    a = Node(x1)
    b = Node(x2)

    a.run()
    b.run()

    while(True):
        print(a.variable)        # global printer
        print(b.variable)        # global printer
        

In this way, Node-a communicates with Node-b and updates its variables, and so does Node-b.

Now I come with a problem: Local printers output updated variable values correctly, but global printers do not. Actually, the global printers always output unchanged values (x1, x2, same as initial).

What's wrong with the code Or how to see the child process variables?

Upvotes: 1

Views: 614

Answers (1)

Guillem
Guillem

Reputation: 2647

You won't be able to do that unless you use any mechanism to communicate with the parent. I recommend you use Manager dicts.

import random
import time
import multiprocessing as mp


class Child(mp.Process):

    def __init__(self, shared_variables):
        super(Child, self).__init__()
        self.shared_variables = shared_variables

    def run(self):
        for _ in range(5): # Change shared variable value 5 times
            self.shared_variables['var'] = random.randint(0, 10)
            self.shared_variables['var1'] = random.randint(0, 10)
            time.sleep(3)


if __name__ == "__main__":
    shared_variables = mp.Manager().dict()
    child = Child(shared_variables)
    child.start()

    while True:
        print('Form parent')
        for k, v in shared_variables.items():
            print(f'-> {k}: {v}')
        print('***********')
        time.sleep(3)

And the output would look like this:

Form parent
-> var: 8
-> var1: 6
***********
Form parent
-> var: 7
-> var1: 7
***********
....

Upvotes: 1

Related Questions