Reputation: 1127
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?
Upvotes: 7
Views: 6712
Reputation: 880897
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
...
Upvotes: 5