2014-12-02 62 views
0

這是一個功能我寫的,增加了一個請求隊列的請求:轉到應用程序掛起

func (self *RequestQueue) addRequest(request *Request) { 

    self.requestLock.Lock() 
    self.queue[request.NormalizedUrl()] = request.ResponseChannel 
    self.requestLock.Unlock() 
} 

,這是它的測試之一:

func TestAddRequest(t *testing.T) { 

    before := len(rq.queue) 

    r := SampleRequests(1)[0] 
    rq.addRequest(&r) 

    if (len(rq.queue) - 1) != before { 
     t.Errorf("Failed to add request to queue") 
    } 
} 

當我運行這個測試時,應用程序掛起。如果我評論這個測試,一切正常。 我認爲問題是函數內部的鎖定。有什麼我做錯了嗎? 感謝您的幫助!

+2

一種可能性:如果任何先前的測試'panic's或在持有'requestLock'時返回錯誤(或成功),可能會發生。標準的做法是在每個'Lock()'之後立即推遲self.requestLock.Unlock(),這樣就可以爲你清理一些東西。 – twotwotwo 2014-12-02 08:01:14

+0

首先,如@twotwotwo提到的,用'defer'解鎖它。其次,你在測試中訪問rq.queue時沒有鎖定,但是如果沒有別的東西在運行,它可能會很好。第三,你沒有足夠的代碼來幫助你調試。 – 2014-12-02 08:34:06

+0

我在代碼的另一部分發現了問題,對不起,我沒有提供,但非常感謝Defer提示。我沒有想到:) – 2014-12-02 09:51:15

回答

0

的問題是在SampleRequests無限循環()函數:

func SampleRequests(num int) []Request { 

    requests := make([]Request, num, num+10) 
    for i := 0; i < len(requests); i++ { 
     r := NewRequest("GET", "http://api.openweathermap.org/data/2.5/weather", nil) 
     r.Params.Set("lat", "35") 
     r.Params.Add("lon", "139") 
     r.Params.Add("units", "metric") 

     requests = append(requests, r) 
    } 

    return requests 
} 

我被檢查,如果i小於在for循環繼續條件陣列的長度。在每次迭代中,一個項目被添加到數組中,長度增加並且for循環繼續執行。