小编pyr*_*ids的帖子

Can Go例程可以共享频道的所有权吗?

我理解通常,如果我希望从Go例程访问范围外的变量,我有责任创建一个由Go例程概念上拥有的副本.这对渠道也是如此,还是免除?

有效的Go #channels用"这可能看起来很奇怪,req := req但在Go中这是一个[原文如此]的法律和惯用语"解释了这一点,指的是这个代码示例:

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
        }()
    }
}
Run Code Online (Sandbox Code Playgroud)

我碰巧在我自己的项目中几乎复制了这个示例代码(除了我使用的是chan struct{}而不是chan int我的信号量,并将其声明为Servefunc的本地代码).盯着它,我想知道是否从多个并发goroutine访问相同的通道真的很好,或者是否需要类似的东西sem := sem.

concurrency channel go race-condition goroutine

2
推荐指数
2
解决办法
774
查看次数

标签 统计

channel ×1

concurrency ×1

go ×1

goroutine ×1

race-condition ×1