M
M
Max Payne2018-03-21 21:39:13
Python
Max Payne, 2018-03-21 21:39:13

Changing class arguments in child process?

I use Python 3.6 and ran into an interesting problem:
Let's say we have a class and some dictionary, when it is initialized, some value is written to this dictionary

class test:
    test_dictionary = {}

    def __init__(self, name):
        self.test_dictionary[name] = [1,2]

Further, during initialization, the child process multiprocessing is launched
import multiprocessing as mp
import time

class test:
    test_dictionary = {}

    def __init__(self, name):
        self.test_dictionary[name] = [1, 2]
        mp.Process(target=self.change_value1, args=(name, 3, 4)).start()

    def change_value1(self, name, new_value1, new_value2):
        mp.Process(target=self.change_value2, args=(name, new_value1, new_value2)).start() # на экране [1, 2] => [3, 4]
        time.sleep(1)
        mp.Process(target=self.change_value2, args=(name, new_value1*2, new_value2*2)).start() # на экране [1, 2] => [6, 8]

    def change_value2(self, name, new_value1, new_value2):
        print(self.test_dictionary[name])
        self.test_dictionary[name] = [new_value1, new_value2]
        print(self.test_dictionary[name])

Why are changes not saved when changing class arguments in a child process? After the process terminates, they return to their default values. The class was given as an example.
PS It means that the values, for some reason, change only locally, although this is a class method.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Max Payne, 2018-03-22
@YardalGedal

The problem turned out to be that each process creates its own copy of the class.
There are two solutions:
1. Replace multiprocessing with threading (no)
2. Use something that allows you to pass information between processes, such as multiprocessing.Value ( Sharing state between processes )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question