Sharing State

This lesson discusses the facilities available in the multiprocessing module to share state amongst processes.

We'll cover the following...

Sharing State

In the previous section we saw how processes can pass objects to eachother using queues or pipes. However, if a process P1 passes an object to process P2, any changes made by P1 to the object after the pass aren't visible to P2 since P2 only receives a copy of the object. For example, consider the below program.

Using queue to pass objects between two processes

from multiprocessing import Process, Queue, Semaphore
import multiprocessing


def child_process(q, sem1, sem2):
    var = q.get()
    print("Child process received var = {0} with id {1} from queue".format(str(var), id(var)))
    sem2.release()
    sem1.acquire()

    print("After changes by parent process var in child process = {0}".format(str(var)), flush=True)


if __name__ == '__main__':
    q = Queue()
    sem1 = Semaphore(0)
    sem2 = Semaphore(0)
    print("This machine has {0} CPUs".format(str(multiprocessing.cpu_c
...