golang http timeout and goroutines accumulation

前端 未结 1 1595
野的像风
野的像风 2021-01-03 16:18

I use goroutines achieve http.Get timeout, and then I found that the number has been rising steadily goroutines, and when it reaches 1000 or so, the program will exit

<
相关标签:
1条回答
  • 2021-01-03 16:26

    Init your chan with 1 instead of 0:

    ch := make(chan Response, 1)

    And remove the defer block that closes and nils ch.

    See: http://blog.golang.org/go-concurrency-patterns-timing-out-and

    Here is what I think is happening:

    1. after the 5s timeout, timeoutHttpGet returns
    2. the defer statement runs, closing ch and then setting it to nil
    3. the go routine it started to do the actual fetch finishes and attempts to send its data to ch
    4. but ch is nil, and so won't receive anything, preventing that statement from finishing, and thus preventing the go routine from finishing

    I assume you are setting ch = nil because before you had that, you would get run-time panics because that's what happens when you attempt to write to a closed channel, as described by the spec.

    Giving ch a buffer of 1 means that the fetch go routine can send to it without needing a receiver. If the handler has returned due to timeout, everything will just get garbage collected later on.

    0 讨论(0)
提交回复
热议问题