This is just an abstract example. test will work as long as it receives messages from test2. Then when they are all done wg.Done() will be called, and application will close after wg.Wait().
package main
import (
"fmt"
"sync"
)
var a = make(chan bool)
var wg sync.WaitGroup
func main() {
go test()
wg.Add(1)
for i := 0; i < 5; i++ {
go test2()
wg.Add(1)
}
wg.Wait()
}
func test() {
defer wg.Done()
for {
val := <-a
fmt.Println(val)
}
}
func test2() {
defer wg.Done()
for i := 0; i < 3; i++ {
a <- true
}
}
At least this is theory, but it doesn't translate well to practice. It correctly displays true 15 times, but then application crashes with a deadlock, because wg.Done() is never called. I'm quite stumped, because this is how it's done in tutorials.
The goroutine created in
testwill never terminate, because of that, the wait group count will never reach zero and it will wait indefinitely.Terminate the endless for-loop after 3 writes and the program should work, because you are reading 3 times from the channel.
Also, you have to call
wg.Addbefore creating the goroutine, not after.wg.Donemay be called before you can add to it, causing a panic.