我正在编写一个程序,该程序使用多个工作进程(预分叉模型),并带有以下代码。
from multiprocessing import Process
for i in range(0,3):
Process(target=worker, args=(i,)).start()
我使用Windows。我注意到,当我希望它们以子进程开始时,它们作为单独的进程运行。如何使它们成为主过程的子过程?
我对使用子进程模块犹豫不决,因为它似乎适合运行外部进程(据我所知)。
更新:似乎Windows不会将新流程作为子流程启动。 Python在Windows中不支持getppid()(获取父级的PID)。
答案 0 :(得分:3)
你似乎在这里混淆术语。子进程是一个单独的进程。创建的进程将是程序主进程的children,从这个意义上讲是子进程。如果你想要线程,那么使用multithreading
代替multiprocessing
,但请注意Python不会为多个线程使用多个内核/ CPU。
我对使用
subprocess
模块犹豫不决,因为它似乎适合运行外部进程
对不起,我不明白这句话。
答案 1 :(得分:3)
你对子进程有什么打击?对我来说,它们是你主要过程的子过程。这是我的示例和返回的输出。
import time, os
from multiprocessing import Process
def worker():
print "I'm process %s, my father is %s" % (os.getpid(), os.getppid())
print "I'm the main process %s" % os.getpid()
for i in range(0,3):
Process(target=worker).start()
输出结果为:
I'm the main process 5897
I'm process 5898, my father is 5897
I'm process 5899, my father is 5897
I'm process 5900, my father is 5897
您有3个子流程附加到主流程...
答案 2 :(得分:1)
简短回答:http://docs.python.org/library/threading.html
更长:我不明白这个问题,aitchnyu。在典型的Unix模型中,进程可以启动的唯一进程是子进程。我有一种强烈的感觉,我们两个之间的词汇冲突,我不知道如何解开。你似乎有一个像“内部过程”的东西;在任何语言或操作系统中都有这样的例子吗?
我可以证明Python的子进程模块被广泛使用。
您编写“...多个工作线程......”您是否已阅读我在此回复顶部第一行中提到的文档?