从一个通道接收到无处的数据。

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

Receiving from a channel into nowhere

问题

太常见了,在阅读Go源代码时,我经常遇到这种模式,其中从通道接收一个值,例如<-doneC,但它没有将结果保存到变量中。

我不明白它的作用。

doneC, _, err := rest.XReceive(eHandler, errHandler)
if err != nil {
	fmt.Println("错误", err)
	return
}
<-doneC
英文:

Too often, reading at Go source code, I encounter this pattern where a value is received from a channel, something such as &lt;-doneC, it does not save the result to a variable.

I don't understand what it does.

doneC, _, err := rest.XReceive(eHandler, errHandler)
if err != nil {
	fmt.Println(&quot;Error&quot;,err)
	return
}
&lt;-doneC

答案1

得分: 5

这是在Go语言中实现异步等待的一种惯用方式。

一个函数启动一个新的goroutine,并将一个"done"通道返回给调用者。

然后调用者执行<-doneC,这基本上是尝试从通道中接收数据,忽略结果。

当goroutine完成时,可以向doneC发送一个虚拟值,或者更好的做法是简单地close它。这作为<-doneC继续执行的信号。

关闭doneC而不是发送虚拟值的附加好处是:(1) 可以同时解除阻塞多个对<-doneC的调用,(2) 如果没有等待的调用者,发送操作将被阻塞,但close操作不会。

英文:

That's an idiomatic way to implement an asynchronous wait in Go.

A function starts a new goroutine and returns a "done" channel to the caller.

The caller then does &lt;-doneC which is basically an attempt to receive from the channel, ignoring the result.

The goroutine, when finished, can then either send a dummy value to doneC or, better yet, simply close it. That acts as the signal for &lt;-doneC to resume execution.

The added benefit of closing doneC instead of sending a dummy value is that (1) multiple calls to &lt;-doneC can be unblocked at the same time, and (2) if none are waiting, the sending will block, but close won't.

huangapple
  • 本文由 发表于 2021年9月11日 21:31:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/69143492.html
匿名

发表评论

匿名网友

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

确定