Search code examples
pythonpython-multiprocessing

explanation of value in multiprocessing? (unexpected output)


I have this code here:

from multiprocessing import Value, Process

def func(x):
    x.value += 1
    print("child process - " + str(x.value))


x = Value("i")
x.value = 0
print("main process - " + str(x.value))

if __name__ == "__main__":
    p1 = Process(target=func, args=(x, ))
    p1.start()
    p1.join()
    p1.close()

print("end - " + str(x.value))

Now, I would expect the output of this code to be:

main process - 0
child process - 1
end - 1

But instead I am getting:

main process - 0
main process - 0
end - 0
child process - 1
end - 1

Can someone explain this to me? I'm new to multiprocessing so I'm probably doing something wrong. Regards


Solution

  • I can confirm that solution suggested by Joran Beasley works. When you put everything under if __name__ == "__main__" it works just like it should