I'm trying to learn Go and I'm using this tutorial.
I've written the following code,
var wg sync.WaitGroup
func foo(c chan int, someValue int) {
defer wg.Done()
c <- someValue * 5
}
func main() {
fooVal := make(chan int)
for i := 0; i < 10; i++ {
go foo(fooVal, i)
wg.Add(1)
}
wg.Wait() // Wait for all routines to complete
close(fooVal) // close channel
for item := range fooVal {
fmt.Println(item)
}
}
Here is my understanding so far,
- I create a channel that receives ints
- I create 10 subroutines, and I add 1 to the waitgroup so I can get them to sync later
- I wait for the routines to complete
- I close the channel so that it doesn't receive any more values
- I loop through the values in the channel to print them
However, I get an error that says:
fatal error: all goroutines are asleep - deadlock!
I'm not sure what this means. My guess is that range
tries to get a value from the channel but it doesn't have any. But that shouldn't be happening because I waited for all routines to complete and then I closed the channel.
What's going on?
The solution for this is to do something like make(chan int, 10)
to give it a buffer, but I'm not sure what a buffer is or why I need it.
Also, I'm not sure what make
does. I've used it to create a map as well. Is it just a constructor?