goroutines deadlock when using channels

Issue

Im new to go lang and I am trying to write a simple recursive algorithm which will use goroutines. I am using channels to receive output from goroutine, but when I try to do so I receive “fatal error: all goroutines are asleep – deadlock!” error. If I comment out channels code everything runs fine.
This is my code:

package main

import (
    "fmt"
    "sync"
)

func main() {
    numbers := []int{2, -1, 10, 4, 3, 6, 22}

    ch := make(chan []int)

    wg := &sync.WaitGroup{}
    wg.Add(1)
    go testFunc(numbers, ch, wg)
    wg.Wait()

    result := <-ch

    fmt.Println("Result: ", result)
}

func testFunc(numbers []int, ch chan []int, wg *sync.WaitGroup) {
    defer wg.Done()
    ch <- numbers
}

What I am doing wrong ? I am assigning value to channel in goroutine and reading it in main. Isn’t that enough to communicate?

Solution

Communication on the unbuffered channel ch succeeds only when both a sender and receiver are ready.

The main function waits on the wait group before receiving the value. The goroutine attempts to send on the channel before call wg.Done. It’s a deadlock.

One fix is to use a buffered channel:

     ch := make(chan []int, 1)

Another fix is to receive on the channel before calling wg.Wait().

result := <-ch
wg.Wait()

Yet another fix is to delete all lines using the wait group. It’s not needed in this specific example.

Answered By – Bayta Darell

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.