Golang Channel Deadlock with Example

Share this blog with others!

In the previous blog, we learned about the Golang channel, Types of Golang channels. 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.

The 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.

0 0 votes
Article Rating

Share this blog with others!
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top