相关疑难解决方法(0)

多个goroutines在一个频道上收听

我有多个goroutines尝试同时在同一个频道上接收.似乎在频道上开始接收的最后一个goroutine获得了价值.这是语言规范中的某个地方还是未定义的行为?

c := make(chan string)
for i := 0; i < 5; i++ {
    go func(i int) {
        <-c
        c <- fmt.Sprintf("goroutine %d", i)
    }(i)
}
c <- "hi"
fmt.Println(<-c)
Run Code Online (Sandbox Code Playgroud)

输出:

goroutine 4
Run Code Online (Sandbox Code Playgroud)

在操场上的示例

编辑:

我才意识到这比我想象的要复杂得多.消息在所有goroutine周围传递.

c := make(chan string)
for i := 0; i < 5; i++ {
    go func(i int) {
        msg := <-c
        c <- fmt.Sprintf("%s, hi from %d", msg, i)
    }(i)
}
c <- "original"
fmt.Println(<-c)
Run Code Online (Sandbox Code Playgroud)

输出:

original, hi from 0, hi from 1, hi from …
Run Code Online (Sandbox Code Playgroud)

go

65
推荐指数
4
解决办法
5万
查看次数

在Golang中同时从多个频道读取

我是Golang的新手.现在我想弄清楚如何在Golang中建立一对一的通道,其设置如下:

说我有两个goroutine numgen1和numgen2同时执行并将数字写入通道num1 resp.NUM2.我想在新进程addnum中添加从numgen1和numgen2发送的数字.我尝试过这样的事情:

func addnum(num1, num2, sum chan int) {
    done := make(chan bool)
    go func() {
        n1 := <- num1
        done <- true
    }()
        n2 := <- num2
        <- done
    sum <- n1 + n2
}
Run Code Online (Sandbox Code Playgroud)

但这似乎很不正确.有人可以给我一些想法吗?

非常感谢您的帮助.

concurrency go channels

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

标签 统计

go ×2

channels ×1

concurrency ×1