Multiple goroutines listening on one channel

前端 未结 5 1562
攒了一身酷
攒了一身酷 2020-11-28 19:49

I have multiple goroutines trying to receive on the same channel simultaneously. It seems like the last goroutine that starts receiving on the channel gets the value. Is thi

5条回答
  •  无人及你
    2020-11-28 20:25

    It is complicated.

    Also, see what happens with GOMAXPROCS = NumCPU+1. For example,

    package main
    
    import (
        "fmt"
        "runtime"
    )
    
    func main() {
        runtime.GOMAXPROCS(runtime.NumCPU() + 1)
        fmt.Print(runtime.GOMAXPROCS(0))
        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)
    }
    

    Output:

    5, original, hi from 4
    

    And, see what happens with buffered channels. For example,

    package main
    
    import "fmt"
    
    func main() {
        c := make(chan string, 5+1)
        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)
    }
    

    Output:

    original
    

    You should be able to explain these cases too.

提交回复
热议问题