猿问

为什么 net/rpc/client 的 Go 方法需要缓冲通道?

我无法弄清楚为什么该方法需要您专门提供缓冲通道。

文档中,

func (*Client) 去

func (client *Client) Go(serviceMethod string, args interface{}, reply interface{}, done chan *Call) *Call

Go 异步调用函数。它返回表示调用的 Call 结构。done 通道将通过返回相同的 Call 对象在调用完成时发出信号。如果 done 为 nil,Go 将分配一个新通道。如果非零,done 必须被缓冲,否则 Go 会故意崩溃。


跃然一笑
浏览 183回答 1
1回答

白板的微信

LeGEC 在他们的评论中提到了这一点。进一步挖掘,您会在 client.go 中找到这一点func (call *Call) done() {&nbsp; &nbsp; select {&nbsp; &nbsp; case call.Done <- call:&nbsp; &nbsp; &nbsp; &nbsp; // ok&nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; // We don't want to block here. It is the caller's responsibility to make&nbsp; &nbsp; &nbsp; &nbsp; // sure the channel has enough buffer space. See comment in Go().&nbsp; &nbsp; &nbsp; &nbsp; if debugLog {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Println("rpc: discarding Call reply due to insufficient Done chan capacity")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}从这里你可以看到,库期望调用是完全异步的。这意味着完成通道必须有足够的容量来完全解耦两个进程(即完全没有阻塞)。此外,当使用 select 语句时,它是执行非阻塞通道操作的惯用方式。
随时随地看视频慕课网APP

相关分类

Go
我要回答