英文:
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 <-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("Error",err)
return
}
<-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 <-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 <-doneC
to resume execution.
The added benefit of closing doneC
instead of sending a dummy value is that (1) multiple calls to <-doneC
can be unblocked at the same time, and (2) if none are waiting, the sending will block, but close
won't.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论