2014-03-28 165 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

相關問題