golang http client里,为什么 writeErrCh 有缓冲 而 responseAndError 无缓冲?

writeErrCh := make(chan error, 1)  // 有缓冲
pc.writech <- writeRequest{req, writeErrCh, continueCh}
resc := make(chan responseAndError) // 无缓冲
pc.reqch <- requestAndChan{
   req:        req.Request,
   ch:         resc,
   addedGzip:  requestedGzip,
   continueCh: continueCh,
   callerGone: gone,
}

golang标准库里,http.net.persistConn 结构的 roundTrip 函数里。为什么 responseAndError 要用无缓冲队列。因此每次写 responseAndError 同时还要判断 callerGone 队列?

//
type requestAndChan struct {
   req *Request
   ch chan responseAndError // unbuffered; always send in select on callerGone
}
阅读 2.1k
2 个回答

按照当时fix说明其中一个原因应该是为了防止goroutine泄露
https://go-review.googlesourc...
但是看现在的逻辑,好像使用有缓冲的也不会出问题

好问题。

背景

  • 一个 persistConn 至少涉及 3 个 goroutine,调用者算一个,剩下两个分别对应底层连接的读、写循环操作。
  • HTTP 1.1 支持 pipelining 技术,即在同个 TCP 连接上连续发送多个 HTTP 请求,而不必等待相应的返回内容。

解说

writeErrCh 如果没有缓冲,persistConn 的写操作将可能被调用者阻塞。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题