【发布时间】:2014-06-27 16:30:57
【问题描述】:
我知道,通常,如果我希望从 Go 例程访问范围外的变量,我有责任创建一个副本以在概念上由 Go 例程拥有。频道也是如此,还是那些被豁免的?
Effective Go #channels 用“写req := req 可能看起来很奇怪,但在 Go 中这样做是 [sic] 合法且惯用的”字样解释了这一点,参考以下代码示例:
var sem = make(chan int, MaxOutstanding)
// (other code, filling sem, defining process(..), etc., omitted)
func Serve(queue chan *Request) {
for req := range queue {
<-sem
req := req // Create new instance of req for the goroutine.
go func() {
process(req)
sem <- 1
}()
}
}
我碰巧在我自己的项目中几乎复制了这个示例代码(除了我使用chan struct{} 而不是chan int 作为我的信号量,并将它声明为Serve 函数的本地)。盯着它看,我想知道从多个并发 goroutine 访问同一个通道是否真的很好,或者是否需要 sem := sem 之类的东西。
【问题讨论】:
-
这个问题与其他一些问题相似 - 您可能会发现它们也提供了丰富的信息。 Reading from multiple channels simultaneously in Golang 和 multiple goroutines listening on one channel
标签: concurrency go race-condition channel goroutine