Go应用在测试包含锁的函数时出现挂起的情况。

huangapple go评论80阅读模式
英文:

Go app hangs when testing a function that contains a lock

问题

这是我写的一个将请求添加到请求队列的函数:

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

当我运行这个测试时,应用程序会卡住。如果我注释掉这个测试,一切都正常工作。
我认为问题出在函数内部的锁定上。我做错了什么吗?
谢谢你的帮助!

英文:

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!

答案1

得分: 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
}

我在for循环的继续条件中检查了i是否小于数组的长度。每次迭代时,都会向数组中添加一个项,长度增加,for循环继续执行。

英文:

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 &lt; len(requests); i++ {
		r := NewRequest(&quot;GET&quot;, &quot;http://api.openweathermap.org/data/2.5/weather&quot;, nil)
		r.Params.Set(&quot;lat&quot;, &quot;35&quot;)
		r.Params.Add(&quot;lon&quot;, &quot;139&quot;)
		r.Params.Add(&quot;units&quot;, &quot;metric&quot;)

		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.

huangapple
  • 本文由 发表于 2014年12月2日 14:22:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/27243114.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定