python - 多处理 python 2.6 的问题

标签 python multiprocessing

我正在尝试构建一个简单的程序,它将触发大量进程,如果主进程被终止,子进程就会终止。我的代码如下所示:

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 行上的 print x,它就不起作用了。这些进程将继续运行,为什么?

此外,我很想知道这是否是实现我想要实现的目标的正确方法。

最佳答案

这对我来说在 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 吗?有programming guidelines与在 Windows 中使用多处理相关。特别是,您需要使用 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

当我杀死 python 中的主线程(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

这是意外的还是不受欢迎的?

关于python - 多处理 python 2.6 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4078925/

相关文章:

Java相当于python/haskell的map()函数,具有多处理/多线程功能?

php - PHP 中的多线程或并行处理

python bottle 导入一个类

python - 如何替换python字符串中的占位符

python - 使用 Python 多处理模块在多个进程之间共享状态

python - SciKit Learn 并行处理 0.17 到 0.18 (Python 2.7)

python - multiprocessing.Process - 为什么 .start() 方法在 IDLE 控制台中不起作用?

python - 如何将字典保存为 JSON 文件?

javascript - 为什么复选框在取消选中时不在 onchange 上提交任何数据

python - 按第一列中的值对数据进行分组