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.