Sharing State Between Processes
suggest changeCode running in different processes does not, by default, share the same data. However, the multiprocessing module contains primitives to help share values across multiple processes.
import multiprocessing
plain_num = 0
shared_num = multiprocessing.Value('d', 0)
lock = multiprocessing.Lock()
def increment():
global plain_num
with lock:
# ordinary variable modifications are not visible across processes
plain_num += 1
# multiprocessing.Value modifications are
shared_num.value += 1
ps = [multiprocessing.Process(target=increment) for n in range(4)]
for p in ps:
p.start()
for p in ps:
p.join()
print("plain_num is %d, shared_num is %d" % (plain_num, shared_num.value))
# Out: plain_num is 0, shared_num is 4
plain_num stays 0 because each process has its own copy. shared_num is a multiprocessing.Value, so the increments are shared when the child uses the parent’s object. That is what fork does. With spawn, the default on Windows and macOS, the module is imported again and this module-level Value and Lock are new objects, so the parent’s shared_num stays 0. The printed 4 is from a run that shared those globals. Start the processes under if __name__ == "__main__" when using spawn. The sample was not run again.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents