【发布时间】:2019-04-17 00:13:46
【问题描述】:
在来自 Go101 站点的 this article 中,我已经阅读了一些关于 stopCh 频道双重选择的技巧(在“2.一个接收者,N 个发送者,唯一的接收者通过关闭附加信号说“请停止发送更多”渠道”)。
您能否描述一下它是如何工作的?我真的需要在实际应用中使用它吗?
UPD:我没有询问有关频道关闭的问题。我已经询问了这部分代码的用法:
// The try-receive operation is to try
// to exit the goroutine as early as
// possible. For this specified example,
// it is not essential.
select {
case <- stopCh:
return
default:
}
// Even if stopCh is closed, the first
// branch in the second select may be
// still not selected for some loops if
// the send to dataCh is also unblocked.
// But this is acceptable for this
// example, so the first select block
// above can be omitted.
select {
case <- stopCh:
return
case dataCh <- rand.Intn(Max):
}
双重选择stopCh的真正用例是什么?
【问题讨论】:
-
在实际应用中肯定会用到,是否需要使用取决于用例。它的工作原理是这样的:tour.golang.org/concurrency/4
-
如我所见,您没有理解我的问题。我要求双重选择频道,而不是近距离通话。
-
给予停止优先权。在第二次选择中,如果同时有工作和停止信号,则随机选择一个。