My question arises from trying to read a channel, if possible, or write it, if possible, using the select statement.
I know that the channels specified as make(chan bool, 1) are buffered, and part of my question is what is the difference between them and make(chan bool) - which this page says is the same as make(chan bool, 0) --- What is the channel point that can hold 0 values ββin it?
See Playground A :
chanFoo := make(chan bool) for i := 0; i < 5; i++ { select { case <-chanFoo: fmt.Println("Read") case chanFoo <- true: fmt.Println("Write") default: fmt.Println("Neither") } }
Exit:
Neither Neither Neither Neither Neither
(Removing the default case results in a deadlock!)
Now look at playground B :
chanFoo := make(chan bool, 1) // the only difference is the buffer size of 1 for i := 0; i < 5; i++ { select { case <-chanFoo: fmt.Println("Read") case chanFoo <- true: fmt.Println("Write") default: fmt.Println("Neither") } }
B output:
Write Read Write Read Write
In my case, pin B is what I want. What are the benefits of unbuffered channels? All the examples that I see on golang.org seem to use them to send one signal / value at a time (and thatβs all I need), but, like in Playground A, the channel is never read or written . What am I missing in my understanding of channels?
go channel
Matt
source share