2010-11-02 84 views
1

我试图建立一个简单的程序,将会触发一个负载的进程,如果主进程被终止,子进程将会死亡。我的代码看起来像这样:多处理python的问题2.6

import time 
def test_proc(name, conn): 
    x = 0 
    while True: 
     print x 
     x += 1 
     conn.poll() 



from multiprocessing import Process, Pipe 

proc_name= ['a', 'b', 'c'] 
procs = [] 
for p in proc_name: 
    parent_conn, child_conn = Pipe() 
    p = Process(target=test_proc, args=(p, child_conn)) 
    procs.append(p) 
    p.start() 

while True: 
    print [(p.is_alive(), 'Pid %s' %(p.pid)) for p in procs] 
    time.sleep(1) 

它的工作原理,但如果我删除第5行打印x它不。这些过程将继续运行,为什么?

另外,我很想知道这是否是正在尝试实现的正确方法。

回答

1

这工作正常,我在Ubuntu:

>>> from time import sleep 
>>> from multiprocessing import Process, Pipe 
>>> 
>>> def test_proc(name, conn): 
...  x = 0 
...  while True: 
...    #print x 
...    x += 1 
...    conn.poll() 
... 
>>> def main(): 
...  proc_name= ['a', 'b', 'c'] 
...  procs = [Process(target=test_proc, args=Pipe()) for p in proc_name] 
...  for p in procs: 
...    p.start() 
...  while True: 
...    print [(p.is_alive(), 'Pid %s' %(p.pid)) for p in procs] 
...    sleep(1) 
... 
>>> main() 
[(True, 'Pid 423'), (True, 'Pid 424'), (True, 'Pid 425')] 
[(True, 'Pid 423'), (True, 'Pid 424'), (True, 'Pid 425')] 
[(True, 'Pid 423'), (True, 'Pid 424'), (True, 'Pid 425')] 
[(True, 'Pid 423'), (True, 'Pid 424'), (True, 'Pid 425')] 
... 

你使用的是Windows,也许?有关于在Windows上使用多处理的programming guidelines。特别是,您需要使用if __name__ == '__main__':来提供入口点。


后来:实际上,有一些我没有得到。在你的原始代码中,你期望杀死线程的父代并让线程继续运行。你是如何在我的代码中杀死父母 - main()?如果线程没有执行I/O,你怎么知道线程还活着?


后来还是:当我运行的线程,我得到这个:

>>> main() 
[(True, 'Pid 940'), (True, 'Pid 941'), (True, 'Pid 942')] 
[(True, 'Pid 940'), (True, 'Pid 941'), (True, 'Pid 942')] 
[(True, 'Pid 940'), (True, 'Pid 941'), (True, 'Pid 942')] 
[(True, 'Pid 940'), (True, 'Pid 941'), (True, 'Pid 942')] 
[(True, 'Pid 940'), (True, 'Pid 941'), (True, 'Pid 942')] 

这:

PID TTY   TIME CMD 
    911 pts/6 00:00:00 python 
    940 pts/6 00:00:29 python 
    941 pts/6 00:00:29 python 
    942 pts/6 00:00:37 python 
    944 pts/5 00:00:00 ps 

当我杀死蟒蛇主线程(按Ctrl - C),我得到这个:

PID TTY   TIME CMD 
    911 pts/6 00:00:00 python 
    940 pts/6 00:00:42 python <defunct> 
    941 pts/6 00:00:50 python <defunct> 
    942 pts/6 00:00:51 python <defunct> 
    946 pts/5 00:00:00 ps 

这是unexpec特德还是不受欢迎?

+0

嗨休,实际上我使用的是Ubuntu 1004,通过监视系统监视器,我注意到在我杀死这个脚本后,三个PID会继续运行,这就是我想要避免的 – MattyW 2010-11-02 17:02:43

+0

仍然不适用于我的队友,但要回答你的问题,我正在寻找的是一个干净的方式,让那些进程死亡,当主进程 – MattyW 2010-11-02 19:33:56