Why can’t variables from the same instance be read in different processes? (Python)

Asked

Viewed 65 times

0

I have two processes going on and I have a class containing a method that modifies a value, as you can see in the code below. The Eventoboton function represents a click to modify a value. But the question is, why does the change only occur within function1 and not function2, or the opposite if it is called the Eventoboton function within function2? If the two use the same instance of the class, if the value of the variable is modified, shouldn’t the value 100 be printed on the two calls to show the value? If someone can explain why this does not happen and what would be the way to "access" the value of the variable in the two processes.

#!/usr/bin/python3
from multiprocessing import Process, Queue



class Aplicativo(object):

    Comando = 0

    def MostraValor(self):

        print("VALOR CMD = ", self.__class__.Comando)

    def InsereValores(self, Cmd):

        self.__class__.Comando = Cmd

    def EventoBotao(self):
        self.InsereValores(100)

App = Aplicativo()


def Funcao1():
    App.EventoBotao()
    App.MostraValor()



def Funcao2():

    App.MostraValor()


if __name__ == "__main__":


    p1 = Process(target=Funcao1)
    p2 = Process(target=Funcao2)

    p1.start()
    p2.start()

    p1.join()
    p2.join()

2 answers

4


You’re not actually accessing the same instance. When you create different processes, the entire state of the program is duplicated in memory and each process only modifies the instance in the memory that belongs to it.

It is not recommended to use the same memory for separate processes. The ideal is to use a Pipe or Queue:

from multiprocessing import Process, Pipe

def escrever_numeros(conn):
    for i in range(10):
        conn.send(i)

if __name__ == '__main__':
    conn1, conn2 = Pipe()
    p = Process(target=escrever_numeros, args=(conn2,))
    p.start()

    while True:
        print('Recebi do outro processo:', conn1.recv())

If really necessary, you can use Value and Array.

As recommendations for your code:

  • Do not use __class__; you are not editing the instance variables, but rather class when you do this. To modify the instance variables, start them in a constructor __init__ and use self.variavel:

    class Aplicativo(object):
    
        def __init__(self):
            self.comando = 0
    
        def insere_valores(self, cmd):
            self.comando = cmd
    
        ...
    
  • Try to use the python style conventions. The name of your variables, for example, should be in lower case letters and separated by _.

  • For an application with the structure of your example, it’s unlikely that you actually have to use multiprocessing. Consider doing it without.

  • Thank you for your reply! I actually have a serial communication in one process and graphical interface running in another. That’s why I summarized to ask the question. I’ve used Queue and everything, but I was seeming insufficient for my needs. That’s why I wanted to modify and read the variable of the "same" instance.

  • @Filipesantos modify variables of the same instance in different processes is not recommended because of synchronization problems; the two processes can write at the same time and this ends up causing more headache than rethinking the structure of the program to be able to use a Queue or Pipe properly. If you want to try, see the documentation that Inkei for Value and Array, but what I would recommend is to invest more time in Queue.

  • Good answer. I think it is worth mentioning that thus: https:/repl.it/repls/InfamousGraveAmurstarfish can solve the problem, because the object on which the processes will work already goes with the modified internal values. These only become 'independent' after each process gets a 'copy' of obj, which in this case already goes with the value 100

1

All this is due to the parallelism model used.

In that reply I talked about Java, but the foundation applies to most modern operating systems. When you order to make a new process, you are making a new program (through the call fork to the OS). Thus, you will have separate processes.

There is difference between Program, Thread and Process?

As seen in the linked response, separate processes have separate memory areas. So unless you create a CPI, one process will not be able to read the other process variable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.