Python 管道子进程在连接后挂起

标签 python python-2.7 multiprocessing python-multiprocessing

希望这是一个相当容易回答的问题。我试图在程序执行时不断向工作进程发送一组数据。问题是,当我尝试加入线程时,程序只是挂起。

我以为工作线程可能终止了,我不需要join,但是当我删除对join 的调用时,我的程序最终挂起。

这是我的代码片段。我试图通过以这种方式使用工作线程来规避大型酸洗操作,因为我之前遇到过队列对象的开销问题。

# Outside of the class definition if that matters here...
def RunTimeWorker(conn, timestep, total_timesteps):
  print "Start worker", timestep, total_timesteps
  while (timestep < total_timesteps):
    data = conn.recv()
    timestep = data[0]
    print timestep, "DATA [" + str(data)
 conn.close()
 print "End worker"

以及调用它的类方法:

def Execute(self):
  parent_conn, child_conn = Pipe()
  p = Process(target=RunTimeTestingWorker,args=(child_conn,0,300))
  p.start()

  for timestep in xrange(300):
    ... 
    # Send required data over to worker
    toProcessArr = [timestep,300,
       # trace data
       ...,...]
    parent_conn.send(toProcessArr)
    ...
  p.join # program hangs here

  #p.join  -- program will hang at end if join is commented

这里我的时间步长已成功更新...

Start worker 0 300
0 DATA [[0, 300, ...]
1 DATA [[1, 300, ...]
2 DATA [[2, 300, ...]
...
299 DATA [[299, 300, ...] # max timesteps are 300
<小时/>

编辑

正如大卫正确指出的那样,这对我来说是一个愚蠢的错误。然而,他关于添加哨兵的评论非常有值(value)。

最佳答案

这是因为您的工作人员正在等待 timestep < total_timesteps ,其中total_timesteps = 300但是timestep = 299 (因为 timestep 位于 xrange(300) 中,即 0..299)。

这里更好的模式是在处理完成时发送某种哨兵值。例如,将工作人员更改为:

while True:
    data = con.recv()
    if data == "DONE":
        break

然后在生产者上:

parent_conn.send("DONE")
p.join()

关于Python 管道子进程在连接后挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28883183/

相关文章:

python - 为什么 Python 2.7 中的 print 括号是自愿的?

java - 有没有更优化的方法在java中进行简单计算?

c - 读取文件时创建不需要的子进程

python - Matplotlib。无法更改第二个 y 轴上的刻度

Python 正则表达式什么也找不到

python - 如何导航 Biopython Entrez efetch 的结果?

python 多处理和 mmap

python - 以字符串格式捕获 **vars() 模式

python - 使用查询提取日期范围

python - 如何在 Python 中创建映射(关联子数组)的列表(数组)