希望这是一个相当容易回答的问题。我试图在程序执行时不断向工作进程发送一组数据。问题是,当我尝试加入线程时,程序只是挂起。
我以为工作线程可能终止了,我不需要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/