views:

132

answers:

3

I don't understand why this simple code

# file: mp.py
from multiprocessing import Process
import sys

def func(x):
    print 'works ', x + 2
    sys.stdout.flush()

p = Process(target= func, args= (2, ))
p.start()
p.join()
p.terminate()
print 'done'
sys.stdout.flush()

creates "pythonw.exe" processes continuously and it doesn't print anything, even though I run it from the command line:

python mp.py

I am running the latest of Python 2.6 on Windows 7 both 32 and 64 bits

A: 

Funny, works on my Linux machine:

$ python mp.py
works  4
done
$

Is the multiprocessing thing supposed to work on Windows? A lot of programs originated in the Unix world don't handle Windows so well, because Unix uses fork(2) to clone processes quite cheaply, but (it is my understanding) that Windows does not support fork(2) gracefully, if at all.

sarnold
Windows doesn't support fork so has to launch a new Python interpreter and reimport the module, i.e. your script. If you haven't protected your start up code with `if __name__ == '__main__':` then it gets run by the child process which is not good.
Dave Webb
... which gets run by the child's child process, which gets run by the child's child's process, which...
Paul McGuire
+2  A: 

According to the programming guidelines for multiprocessing, on windows you need to use an if __name__ == '__main__':

macedoine
+11  A: 

You need to protect then entry point of the program by using if __name__ == '__main__':.

This is a Windows specific problem. On Windows your module has to be imported into a new Python interpreter in order for it to access your target code. If you don't stop this new interpreter running the start up code it will spawn another child, which will then spawn another child, until it's pythonw.exe processes as far as the eye can see.

Other platforms use os.fork() to launch the subprocesses so don't have the problem of reimporting the module.

So your code will need to look like this:

from multiprocessing import Process
import sys

def func(x):
    print 'works ', x + 2
    sys.stdout.flush()

if __name__ == '__main__':
    p = Process(target= func, args= (2, ))
    p.start()
    p.join()
    p.terminate()
    print 'done'
    sys.stdout.flush()
Dave Webb
such an easy detail, so easy to missthat worked, thanks
lj8888