Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

throw: all goroutines are asleep - deadlock

Tags:

Given the following simple Go program

package main  import (     "fmt" )  func total(ch chan int) {     res := 0     for iter := range ch {         res += iter     }     ch <- res }  func main() {     ch := make(chan int)     go total(ch)     ch <- 1     ch <- 2     ch <- 3     fmt.Println("Total is ", <-ch) } 

I am wondering if someone can enlighten me as to why I get

throw: all goroutines are asleep - deadlock! 

thank you

like image 249
adk Avatar asked Sep 13 '12 01:09

adk


People also ask

How do you wait for Goroutines to finish?

The WaitGroup type of sync package, is used to wait for the program to finish all goroutines launched from the main function. It uses a counter that specifies the number of goroutines, and Wait blocks the execution of the program until the WaitGroup counter is zero.

What is a deadlock Golang?

yourbasic.org/golang. A deadlock happens when a group of goroutines are waiting for each other and none of them is able to proceed.

What are go routines?

A goroutine is a function that executes simultaneously with other goroutines in a program and are lightweight threads managed by Go. A goroutine takes about 2kB of stack space to initialize.


1 Answers

As you never close the ch channel, the range loop will never finish.

You can't send back the result on the same channel. A solution is to use a different one.

Your program could be adapted like this :

package main  import (     "fmt" )  func total(in chan int, out chan int) {     res := 0     for iter := range in {         res += iter     }     out <- res // sends back the result }  func main() {     ch := make(chan int)     rch  := make(chan int)     go total(ch, rch)     ch <- 1     ch <- 2     ch <- 3     close (ch) // this will end the loop in the total function     result := <- rch // waits for total to give the result     fmt.Println("Total is ", result) } 
like image 143
Denys Séguret Avatar answered Sep 29 '22 18:09

Denys Séguret