Golang Buffered Channel | Avoid Deadlock

Golang Buffered Channel

In the previous blog, we learned about Channel in Golang. This time we will learn about Buffered Channel in Golang.

You should have knowledge about Golang Channel in order to understand the Golang Buffered Channel. click here to read.

Golang Buffered Channel

Golang Buffered Channel gives an internal memory to channels to avoid deadlock.

make ( chan int, <buffer> )

ch := make(chan int, 50)

This buffer stores the data passed into the channel and helps us to avoid to deadlock which occur when the sending channels become more than expected.

Example:

func main() {
	ch := make(chan int, 50)
	wg.Add(2)
	go func(ch <-chan int) {
		i := <-ch
		fmt.Println("Value of Channel i =", i)
		wg.Done()
	}(ch)
	go func(ch chan<- int) {
		var i int
		i = 17
		ch <- i
		ch <- i + 18
		wg.Done()
	}(ch)
	wg.Wait()

Output:

Value of Channel i = 17

The above example is taken from above, where there are two sending channels but a single receiving channel, but this time we don’t get any kind of error, because we have defined buffer for the channel and the values are stored internally and are removed from the buffer once receiving channel asks for it.

In the Golang Channels Deadlock section, we had seen one way to solve channel deadlock. That was following the equilibrium rule:

Number of Sending Channels = Number of Receiving Channels

But, this is not true every time, it may be possible that the data is sent into the channel at the interval of an hour and thus the equilibrium is not maintained here.

Buffered Channel helps the user to get away from this state, this creates an internal buffer/memory and stores the sent data and sends it to the receiving channel when it asks for it. Here the frequency of sending and receiving channels may or may not be the same.

Learn more about Channels in Golang from the official Documentation.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *