More on channels

When you create a channel in Go with ch := make(chan bool), an unbufferedchannel for bools is created. What does this mean foryour program? For one, if you read (value := <-ch) it will block until thereis data to receive. Secondly anything sending (ch <- true) will block until thereis somebody to read it. Unbuffered channels make a perfect tool forsynchronizing multiple goroutines.

But Go allows you to specify the buffer size of a channel, which is quite simplyhow many elements a channel can hold. ch := make(chan bool, 4), createsa buffered channel of bools that can hold 4 elements. The first 4 elements inthis channel are written without any blocking. When you write the 5th

In conclusion, the following is true in Go:

[\textsf{ch := make(chan type, value)}\left{\begin{array}{ll}value == 0 & \rightarrow \textsf{unbuffered} \value > 0 & \rightarrow \textsf{buffer }{} value{} \textsf{ elements}\end{array}\right.]

When a channel is closed the reading side needs to know this. The following codewill check if a channel is closed.

  1. x, ok = <-ch

Where ok is set to true the channel is not closedand we’ve read something. Otherwise ok is set to false. In that case thechannel was closed and the value received is a zero value of thechannel’s type.