Why is the class attribute unchanged?

2

I just need to send a command from one process to another, but I wanted to understand why when modifying the variable within a function, it does not appear in another function.

from  multiprocessing import Process
import time

ComandoSerial = 0

class teste():

    var = 0

    def __init__(self):
        self.var2 = 0

    def funcao(self):
        self.__class__.var = 1
        self.var2 = 1

    def funcao2(self):
        self.__class__.var = 2
        self.var2 = 2

    def funcao3(self):
        self.__class__.var = 3
        self.var2 = 3

    def retorna(self):
        return  self.__class__.var

    def retorna2(self):
        return self.var2


test = teste()

def Teste1():
    test.funcao3()

def Teste2():
    time.sleep(0.2)
    print("VALOR = ", test.retorna())


p  = Process(target= Teste1)
p1 = Process(target= Teste2)


def main():
    p.start()
    p1.start()
    p.join()
    p1.join()


if __name__ == "__main__":
    main()

The problem is that I put the value 3, but reading it always returns 0.

    
asked by anonymous 18.12.2017 / 12:47

1 answer

2

If this question is an extension of the previous one, about inter-process communication, you should have followed the tips given to you in it. As I said, the variables are not shared between processes and, in this way, in each process there will be a different instance; so that changes made in one process are not reflected in the others (if you give print inside the __init__ method you will see that it is called 3 times: one in the main process and another two in manually created processes.)

To communicate both processes, you can use multiprocessing.Pipe :

from multiprocessing import Process, Pipe

class Foo:
    # Classe de teste, não tente isso em casa
    def __init__(self):
        self.value = 0

def receiver(stream):
    obj = stream.recv()
    obj.value = 2
    stream.send(obj)
    stream.close()

def sender(stream):
    obj = Foo()
    print("Antes:", obj.value)
    stream.send(obj)
    obj = stream.recv()
    print("Depois:", obj.value)
    stream.close()

if __name__ == '__main__':
    parent, child = Pipe()

    p1 = Process(target=receiver, args=(child,))
    p2 = Process(target=sender, args=(parent,))

    p1.start()
    p2.start()

    p1.join()
    p2.join()

In process 2, running the sender function, I create a new object Foo and display the initial value 0; after, I send it through the pipe to the other process; in process 1, running receiver , I read the pipe object, change the value of the attribute to 2 and return it via pipe ; back in process 2, I read the response from process 1 and display again the value of the attribute, which will be modified.

    
18.12.2017 / 14:20