using golang channels. GETTING "all goroutines are asleep – deadlock!"

Issue

iam currently playing around with go routines, channels and sync.WaitGroup. I know waitgroup is used to wait for all go routines to complete based on weather wg.Done() has been called enough times to derement the value set in wg.Add().
i wrote a small bit of code to try to test this in golang playground. show below

var channel chan int
var wg sync.WaitGroup


func main() {

  channel := make(chan int)
  mynums := []int{1,2,3,4,5,6,7,8,9} 
  wg.Add(1)

  go addStuff(mynums)
  wg.Wait()
  close(channel)
  recieveStuff(channel)
 }

 func addStuff(mynums []int) {

   for _, val := range mynums {
       channel <- val
   }
   wg.Done()
 }

 func recieveStuff(channel chan int) {
    for val := range channel{
    fmt.Println(val)
 }
} 

Iam getting a deadlock error. iam trying to wait on the routing to return with wg.Wait()? then, close the channel. Afterwards, send the channel to the recievestuff method to output the values in the slice? but it doesnt work. Ive tried moving the close() method inside the go routine after the loop also as i thought i may of been trying to close on the wrong routine in main(). ive found this stuff relatively confusing so far coming from java and c#. Any help is appreciated.

Solution

The call to wg.Wait() wouldn’t return until wg.Done() has been called once.

In addStuff(), you’re writing values to a channel when there’s no other goroutine to drain those values. Since the channel is unbuffered, the first call to channel <- val would block forever, resulting in a deadlock.

Moreover, the channel in addStuff() remains nil since you’re creating a new variable binding inside main, instead of assigning to the package-level variable. Writing to a nil channel blocks forever:

channel := make(chan int) //doesn't affect the package-level variable

Here’s a modified example that runs to completion by consuming all values from the channel:

https://play.golang.org/p/6gcyDWxov7

Answered By – c.P.u1

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.