2014-03-28 263 views
0

我在python中使用线程模块来做I/O绑定处理的一些测试。python多线程连接导致挂起

基本上,我只是逐行阅读一个文件并同时写出它。

我把阅读和写作圈在单独的线程,并使用队列传递间的数据:如果我运行它上面的

q = Queue() 
rt = ReadThread(ds) 
wt = WriteThread(outBand) 

rt.start() 
wt.start() 

,它工作正常,但在执行结束的解释崩溃。 (?任何想法,为什么)

如果我添加:

rt.join() 
wt.join() 

末,解释只是挂起。任何想法为什么?

的ReadThread和WriteThread类的代码如下:

class ReadThread(threading.Thread): 
    def __init__(self, ds): 
     threading.Thread.__init__(self) 
     self.ds = ds #The raster datasource to read from 

    def run(self): 
     reader(self.ds) 

class WriteThread(threading.Thread): 
    def __init__(self, ds): 
     threading.Thread.__init__(self) 
     self.ds = ds #The raster datasource to write to 

    def run(self): 
     writer(self.ds)   


def reader(ds): 
    """Reads data from raster, starting with a chunk for three lines then removing/adding a row for the remainder""" 

    data = read_lines(ds) 
    q.put(data[1, :]) #add to the queue 
    for i in np.arange(3, ds.RasterYSize):   
     data = np.delete(data, 0, 0) 
     data = np.vstack([data, read_lines(ds, int(i), 1)])    
     q.put(data[1,:]) # put the relevant data on the queue 


def writer(ds): 
    """ Writes data from the queue to a raster file """ 
    i = 0 
    while True: 
     arr = q.get() 
     ds.WriteArray(np.atleast_2d(arr), xoff = 0, yoff = i) 
     i +=1 
+0

什么是'outBand'和'ds'?如果它是一个无限循环的写入/读取,那么'.join()'将永远挂起,因为它期望线程返回某种值。从'.join()' - Python的文档中等待直到线程终止。这会阻塞调用线程,直到调用join()方法的线程终止 - 通常或通过未处理的异常 - 或直到发生可选的超时。* – Torxed

+0

解释器如何崩溃? –

回答

0

呼叫q.get()将无限阻塞的情况下,你的Queue是空的。

您可以尝试使用get_nowait(),但是您必须确保在到达writer函数时,Queue中有一些内容。

0

wt.join()等待线程完成,它永远不会做,因为在在writer左右的无限循环。为了使它完成,加

q.put(None) 

reader最后一行,并更改writer

def writer(ds): 
    """ Writes data from the queue to a raster file """ 
    for i, arr in enumerate(iter(q.get, None)): 
     ds.WriteArray(np.atleast_2d(arr), xoff = 0, yoff = i) 

iter(q.get, None)q直到q.get回报None得到的值。为了进一步简化代码,我添加了enumerate

相关问题