5

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?

3
  • I tested locally and it actually works, which OS platform are you using? Is it Windows?
    – noxdafox
    Apr 22, 2018 at 9:01
  • I tried it again and it doesn't work! I got it to work once, but it doesn't work anymore. I'm on Windows. Any ideas why this is happening? Apr 22, 2018 at 22:20
  • I was answering the question but you canceled it... let me try again.
    – noxdafox
    Apr 23, 2018 at 7:04

1 Answer 1

6

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()
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.