Multiple goroutines listening on one channel

前端 未结 5 1541
攒了一身酷
攒了一身酷 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:23

    Late reply, but I hope this helps others in the future like Long Polling, "Global" Button, Broadcast to everyone?

    Effective Go explains the issue:

    Receivers always block until there is data to receive.

    That means that you cannot have more than 1 goroutine listening to 1 channel and expect ALL goroutines to receive the same value.

    Run this Code Example.

    package main
    
    import "fmt"
    
    func main() {
        c := make(chan int)
    
        for i := 1; i <= 5; i++ {
            go func(i int) {
            for v := range c {
                    fmt.Printf("count %d from goroutine #%d\n", v, i)
                }
            }(i)
        }
    
        for i := 1; i <= 25; i++ {
            c<-i
        }
    
        close(c)
    }
    

    You will not see "count 1" more than once even though there are 5 goroutines listening to the channel. This is because when the first goroutine blocks the channel all other goroutines must wait in line. When the channel is unblocked, the count has already been received and removed from the channel so the next goroutine in line gets the next count value.

提交回复
热议问题