Search code examples
gochannel

Golang routine with unbuffered channel


I am reading the book Go in action.

This is how the unbuffered channel are described:

An unbuffered channel is a channel with no capacity to hold any value before it’s received. These types of channels require both a sending and receiving goroutine to be ready at the same instant before any send or receive operation can complete. If the two goroutines aren’t ready at the same instant, the channel makes the goroutine that performs its respective send or receive operation first wait. Synchronization is inherent in the interaction between the send and receive on the channel. One can’t happen without the other.

The book use the following figure to illustrate the unbuffered channel:

enter image description here

So I just wonder how about if there are three or more goroutines which share the same channel?

For example, three goroutines GA GB GC share the same channel c

Now once GA send message through c, how do we make sure that both GB and GC will receive the message? Since as the book said:

These types of channels require both a sending and receiving goroutine to be ready at the same instant

Which means when two goroutines exchange the message, the third must've lost the message.

Is this the right way to think in this scenario?


Solution

  • A message sent through a channel is delivered to exactly one receiving goroutine.

    Assuming you have three goroutines, one sending and two receiving, the sending goroutine needs to send two messages for both the receiving goroutines to unblock, like this:

    var c = make(chan int)
    
    go func() { fmt.Printf("got %d\n", <-c) }()
    go func() { fmt.Printf("got %d\n", <-c) }()
    
    c <- 1
    c <- 2
    

    Also notice that this also requires the receiving goroutines to read exactly one message each. If they were to do it in a loop, one of them might receive both messages and the other none.