Anish Shanbhag
Anish Shanbhag

Reputation: 424

Multiprocessing Event not Working

I have written the following code in Python 3 using the multiprocessing module. It's more of a test script to see how to use Event. However, it's not working.

import multiprocessing, time

from multiprocessing import Process, Event

event = Event()

def f(n):

    if n == 1:

        print("starting")

        event.wait()

        print("Done!")


    if n == 2:

        time.sleep(3)

        event.set()

        print("setting")

if __name__ == "__main__":

    p1 = Process(target = f, args = (1,))
    p2 = Process(target = f, args = (2,))

    p1.start()

    p2.start()

    time.sleep(1000)

However, when I run this I only get the output:

starting
setting

I want to get the output:

starting
setting
Done!

But for some reason the p1 Process is not moving on with its code after event.set() has been called by the p2 process.

Any ideas why this is happening?

Upvotes: 5

Views: 4726

Answers (1)

noxdafox
noxdafox

Reputation: 15060

From the multiprocessing programming guidelines.

Explicitly pass resources to child processes

... it is better to pass the object as an argument to the constructor for the child process.

Apart from making the code (potentially) compatible with Windows ...

On Windows, you need to pass the shared objects to the Process constructor list of arguments. Otherwise, the child process will get a brand new copy instead of the parent's one. This is why f(1) hangs, it is waiting on another Event object.

Just change the code like this.

def f(n, event):
    if n == 1:
        print("starting")
        event.wait()
        print("Done!")
    elif n == 2:
        time.sleep(3)
        event.set()
        print("setting")

if __name__ == "__main__":
    event = Event()  # one instance of Event only

    p1 = Process(target = f, args = (1, event))
    p2 = Process(target = f, args = (2, event))
    p1.start()
    p2.start()
    p1.join()
    p2.join()

Upvotes: 7

Related Questions