简体   繁体   中英

Go app hangs when testing a function that contains a lock

This is a function I wrote that adds a request to a request queue:

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

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

and this is one of its tests:

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")
    }
}

When I run this test, the application hangs. If I comment out this test, everything works fine. I think the problem is the locking inside the function. Is there something that I'm doing wrong? Thanks for your help!

The problem was an infinite loop in the SampleRequests() function:

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 was checking if i was less than the length of the array in the continuation condition of the for loop. With each iteration, an item was added to the array, the length increased and the for loop continued executing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM