希望这是一个相当容易回答的问题。我正在尝试在程序执行期间不断向工作进程发送一组数据。问题是,当我尝试加入该线程时,该程序就会挂起。
我认为也许工作人员终止了,我不需要join
,但是当我删除对join
的呼叫时,我的程序会在最后挂起。
以下是我的代码片段。我试图以这种方式使用工人来规避大型酸洗操作,因为我之前遇到过Queue对象的开销问题。
# 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
修改
大卫如此正确地指出,这对我来说是一个愚蠢的错误。但是,他关于增加哨兵的评论非常有价值。
答案 0 :(得分:3)
这是因为您的工作人员正在等待timestep < total_timesteps
,其中total_timesteps = 300
但timestep = 299
(因为timestep
位于xrange(300)
,即0..299)
这里更好的模式是在处理完成后发送某种哨兵值。例如,将worker更改为:
while True:
data = con.recv()
if data == "DONE":
break
然后是制片人:
parent_conn.send("DONE")
p.join()