Wicked Bot Wicked Bot -4 years ago 78
Python Question

Python multiprocessing not synchronized

I'm having the problem with multiprocessing synchronization
The following code:

from multiprocessing import Process
list = [1,2,3,4,5]
def function1():
for i in range (5):
print list[i]

if __name__ == '__main__':
for num in range(2):

The result is


How do i get the processes to work in order? E.g: Process1 works with i=1, in mean time Process2 works with i=2 and so on?

Answer Source

What your function does is printing the numbers 1 to 5 regardless of which process it is being executed in. The reason you see 11, 22, etc. is because both progresses are running in "parallel" so they are printing the values "at the same time".

You need to pass the process number to the function so it knows what to print, then all your function has to do is print the process number.

This should work:

from multiprocessing import Process
list = [1,2,3,4,5]
def function1(x):
    print x

if __name__ == '__main__':
    for num in range(2):
        Process(target=function1, args=[list[num]]).start()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download