Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my code not spawning two processes?

My code is not spawning 2 processes, and I have no idea why. I'm using Process from multiprocessing python library.

import os
from multiprocessing import Process

def dummy():
    while True:
        print(os.getpid())

p1 = Process(target=dummy())
p2 = Process(target=dummy())
p1.start()
p2.start()
p1.join()
p2.join()

Expected result: 2 processes created - visible in windows 7 task manager as well as I am having 2 different process id printed by my code

Actual Result: Only one python process running, only one process id is being printed out.

3480
3480
3480
like image 827
Wojtas.Zet Avatar asked Dec 23 '22 21:12

Wojtas.Zet


1 Answers

Your code isn't doing what you think it's doing. On the first of these lines:

p1 = Process(target=dummy())

you're calling the dummy() function. If you add some print statements, you'll see that you never go beyond this line. Because calling dummy() starts an infinite loop in the main process, and the loop just prints the main process's pid forever.

Do this instead:

p1 = Process(target=dummy)
p2 = Process(target=dummy)

That is, don't invoke dummy, just pass the function object. Then the later

p1.start()

(etc) will invoke dummy() in a new process, which is what you intended.

like image 164
Tim Peters Avatar answered Jan 10 '23 15:01

Tim Peters