Golang Channel Deadlock with Example

Golang Channel Deadlock with Example

In the previous blog, we learned about Golang channel, Types of Golang Channel. This time we are going to look at one of the most important topic for Golang Channels i.e Deadlock in Golang Channel.

Click to read about Golang Channel, Types of channels.

Golang Channel Deadlock

The number of channels is limited and whenever we try to receive or send value from and to the channel out of number, a deadlock occurs.

1. Receiving channels more than expected

	go func(ch <-chan int) {
		i := <-ch
		j := <-ch
		fmt.Println("Value of Channel i,j =", i, j)
		wg.Done()
	}(ch)

Error:- fatal error: all goroutines are asleep – deadlock!

Here, there is only a single channel from where data is sent, and two receiving channels and thus Deadlock occurs.

2. Sending Channels more than expected

	go func(ch chan<- int) {
		var i int
		i = 17
		ch <- i
		ch <- i + 18
		wg.Done()
	}(ch)

Error:- fatal error: all goroutines are asleep – deadlock!

In both the situation same kind of error is received.

Solution to resolve Channel Deadlock.

Number of Sending Channels = Number of Receiving Channels

package main

import (
	"fmt"
	"sync"
)

var wg sync.WaitGroup = sync.WaitGroup{}

func main() {
	ch := make(chan int)
	wg.Add(2)
	go func(ch <-chan int) {
		i := <-ch
		j := <-ch
		fmt.Println("Value of Channel i,j =", i,j)
		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,j = 17 35

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 *