In the link below, one of the replies given on the difference between unbuffered vs buffered channel of 1 capacity is that if "the channel is unbuffered (capacity is zero), then communication succeeds only when the sender and receiver are both ready".
What does it mean exactly when the author says the sender and receiver are both ready? Chronologically, am I right to say that one has to come before the other? And if so, am I also right to say that the receiver has to be ready first before the sender?
The differences between channel buffer capacity of zero and one in golang
I been trying to look for explanations on both official and unofficial channels. However, I haven’t found a satisfactory answer yet. The closest I have come is from the explanation below.
Does this mean that any code written below ch <- "C" (if capacity = 3) will still run? Going back to my original question on the difference between capacity 0 vs 1, does this mean that any code below the sender will not run (for capacity = 0)? On the other hand, if capacity = 1, the code below the sender will still run so long even if it is at full capacity of 1?
https://www.golinuxcloud.com/golang-buffered-channel/
Thank you!
>Solution :
What does it mean exactly when the author says the sender and receiver are both ready?
It means that one goroutine is executing receive and that another goroutine is executing send. It does not matter which goroutine begins the operation first.
To put this another way, a sending goroutine blocks until another goroutine receives on the channel.
Contrast this with a buffered channel with available capacity. A goroutine can complete send to the channel without waiting for another goroutine to receive on the channel.
Here’s an example that illustrates the difference between an unbuffered and buffered channel.
sleepRecv := func(c chan int) {
time.Sleep(time.Second)
<-c
}
b0 := make(chan int, 0)
go sleepRecv(b0)
start := time.Now()
b0 <- 0 // must wait for recv in goroutine
fmt.Println(time.Since(start)) // prints 1s
b1 := make(chan int, 1)
go sleepRecv(b1)
start = time.Now()
b1 <- 0 // does not wait for recv in goroutine
fmt.Println(time.Since(start)) // prints 0s