6

I have two processing running that access an imported module like that:

import foo

def bar():
  while True:
    foo.a = True

def baz():
  while True:
    print foo.a

p1 = Process(target=bar)
p2 = Process(target=baz)
p1.start()
p2.start()

It seems that each process have their own instance of module foo, bar() changes value to True, but in baz() it's False. Any workaround?

9
  • Lookup queues and pipes
    – muddyfish
    Commented Aug 19, 2015 at 13:02
  • @muddyfish that's just for communication though, isn't it?
    – akalikin
    Commented Aug 19, 2015 at 13:03
  • Yes, apart from that, you can't change objects that aren't thread friendly.
    – muddyfish
    Commented Aug 19, 2015 at 13:04
  • 3
    Doesn't Process mean a real process (ie with separate memory space)? In that case it's expected that they have own instances of modules. What do you want to do? Communicate? In the documentation it says how to do that (queues, pipes and shared memory).
    – skyking
    Commented Aug 19, 2015 at 13:10
  • @skyking not really communicate, but force them to have the same instance of foo. Or pass it as an argument somehow
    – akalikin
    Commented Aug 19, 2015 at 13:11

1 Answer 1

5

Unlike threads, separate processes do not share memory. There are ways, however, to share data between separate processes. One way is to use a mp.Value:

foo.py:

import multiprocessing as mp
a = mp.Value('b', False)

then the script

import time
import foo
import multiprocessing as mp

def bar():
    foo.a.value = True

def baz():
    for i in range(10**5):
        print foo.a.value

if __name__ == '__main__':
    p2 = mp.Process(target=baz)
    p2.start()
    time.sleep(0.5)
    p1 = mp.Process(target=bar)
    p1.start()

yields

0
0
0
...
1
1
1
...

For sharing a boolean value, an mp.Event is perhaps a better option:

foo.py:

import multiprocessing as mp
a = mp.Event()

script.py:

def bar():
    foo.a.set()

def baz():
    for i in range(10**5):
        print foo.a.is_set()

yields

False
False
False
...
True
True
True
... 

Not the answer you're looking for? Browse other questions tagged or ask your own question.