Processes run in separate memory-spaces, which means global variables cannot be shared. The documentation has a section titled Sharing state between processes that discusses some ways around this when there's a need.
Here's a runnable one of those ways applied along the lines of the pseudocode in your question. It uses an array
type code of 'i'
for an integer because there isn't one specifically for boolean values — but that's OK because in Python booleans are a subclass of int
.
Note that the current value of Value
shared memory object must be accessed through its value
attribute as shown. This is because they are implemented as object proxies with an associated Lock
to prevent concurrent access. The overhead of having to do this can significantly reduce any gains obtain from the multiprocessing itself depending on exactly what you're trying to do.
import multiprocessing
import time
def func1(boolVar):
if boolVar.value:
boolVar.value = False
def func2(boolVar):
time.sleep(1) # For testing, give other process time to execute.
print(bool(boolVar.value)) # Show current "truthiness".
if __name__ == '__main__':
boolVar = multiprocessing.Value('i', True) # Create value in shared memory.
p1 = multiprocessing.Process(target=func1, args=(boolVar,))
p2 = multiprocessing.Process(target=func2, args=(boolVar,))
p1.start()
p2.start()
p1.join()
p2.join()