Channels are commonly used to communicate messages among goroutines in golang. In this post, I will briefly introduce the channels in golang. Goroutines are light-weight threads in golang. When a goroutine wants to communicate with another goroutine, it can use a channel to send messages to that goroutine. Channels are like messages queues. The data type of the messages that can flow in the queue is an important aspect of a channel. The below statement can be used to create a channel:
ach := make(chan int)
The int specifies the data type of the messages that can be sent to or receive from a channel. There two types of channels. One is called unbuffered channel, while the other is called buffered channel. The one created above is called unbuffered channel. There is an variation for the make statement to create channels. Take the below statement for example,
bch := make(chan int, 10)
This creates a channel with capability 10. It means a goroutine can send at most 10 messages without blocking. Unlike buffered channels, if a goroutine sends a message to an unbuffered channel, it will be blocked until another goroutine receives the message. The below two statements can be used to send or receive messages on a channel:
ach <-8 //send a message to a channel
aInt := <-ach //receive a message from a channel
One notable thing about blocking on unbuffered or buffered channels when they are full is that if a channel blocks because it sends a message to a channel, only after the message has been received by another channel, the blocking goroutine has a chance to be waken up. This means the sending goroutine will only be resumed after the receiving goroutine completes the message receiving.