0
votes

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?

1
You're waiting for the goroutine before receiving from the channel. You have an unbuffered channel here, so you don't need the wait group, nor do you need the goroutine at all.JimB

1 Answers

4
votes

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.