Multiprocessing synchronization between multiple processes (Python)

So there in college practical class was an exercise:

"Create program that defines shared value as 0, then creates and starts 500 processes, each of which increases value of shared value by 1, and finally in the end prints shared value. Run this code few times and see what happens, explain...."

Final version looks like:

from multiprocessing import Process, Value


n=Value('i', 0)

def fun():
        n.value+=1

for i in range(500):
        p=Process(target=fun).start()

print n.value

Output value varies in range 420-480 and i understand why.
The questions is how to make it always 500 if it possible? I've been reading Python docs and have found possible solution - Semaphore, but maybe I didn't understand it well..
In the case of Semaphore code looks:

from multiprocessing import Process, Value, Semaphore

n=Value('i', 0)
sem=Semaphore()

def fun():
        sem.acquire()
        n.value+=1
        sem.release()

for i in range(500):
    p=Process(target=fun).start()
print n.value

In this case the final output varies in range 492-495 - way better.

P.S. Do not advise me to use threads from threading class - question is about multiprocessing.

Upvotes: 0

Views: 2417

Answers (1)

Abel Riboulot
Abel Riboulot

Reputation: 178

Your processes are not joined. Your lock therefore works, but the value of n is displayed before all of the processes are done to increment it, hence n<500. You can try the following code:

from multiprocessing import Process, Value, Semaphore

n=Value('i', 0)
sem=Semaphore()

def fun():
        sem.acquire()
        n.value+=1
        sem.release()

pcs=[]
for i in range(500):
    p=Process(target=fun)
    pcs.append(p)
    p.start()
for i in pcs:
    i.join()
print n.value

Upvotes: 2

Related Questions