开发者

Python multiprocessing continuously spawns pythonw.exe processes without doing any actual work

开发者 https://www.devze.com 2023-01-09 23:45 出处:网络
I don\'t understand why th开发者_运维问答is simple code # file: mp.py from multiprocessing import Process

I don't understand why th开发者_运维问答is 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


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消