process in python

4

I'm trying to change an external variable within a process but it is not working. I created a simple test class:

from multiprocessing import Process
class Classe():
  def __init__(self, parent=None):
    self.variavel="antes"
    self.p = Process(target=self.f, args=(self.variavel,))

  def f(self, variavel2):
    variavel2="depois"
  def g(self):
    self.p.start()
    self.p.join()
    print self.variavel



teste=Classe()
teste.g()

But when I run this, it prints the old value of the variable, someone knows how to access a normal variable within the process, I tried to use self.variavel but it did not work too.

    
asked by anonymous 22.06.2016 / 16:46

1 answer

4

A little more complex than you might think at first. This ( Sharing state between processes ) when it's with integers it's a bit simpler than with strings. EX with integers:

from multiprocessing import Process, Value

class Classe():

    def __init__(self, parent=None):
        self.variavel=Value('i', 0)
        self.p = Process(target=self.f, args=())

    def f(self):
        self.variavel.value = 2

    def g(self):
        self.p.start()
        self.p.join()

    def get_var(self):
        return self.variavel.value

Example with strings (I believe this is what you want) we need to import ctypes c_char_p for this case:

from multiprocessing import Process, Value, Manager
from ctypes import c_char_p

class Classe():

    def __init__(self, parent=None):
        manager = Manager()
        self.variavel=manager.Value(c_char_p, "antes")
        self.p = Process(target=self.f, args=())

    def f(self):
        self.variavel.value = "depois"

    def g(self):
        self.p.start()
        self.p.join()

    def get_var(self):
        return self.variavel.value

Use for the two cases above:

teste=Classe()
print(teste.get_var())
teste.g()
print(teste.get_var())
    
22.06.2016 / 17:02