in the main routine. If the last loop manages to read all the channel values the first <-myCh will block, the waitgroup will never get done, the channel will never close and the program doesn’t terminate, potentially crashing with the deadlock output.
Thanks for you help. I’m not sure learning more about the waitgroup code. It seems most people don’ use it. Anyway, I feel I kind of cheated, but I don’t get a race condition anymore.
This is what I ended up with:
package main
import (
"fmt"
"sync"
)
var wq sync.WaitGroup
func main() {
myCh := make(chan string)
wq.Add(2)
go func() {
defer wq.Done()
for i := 0; i < 10; i++ {
myCh <- "anom 1"
}
}()
go func() {
defer wq.Done()
for i := 0; i < 10; i++ {
myCh <- "anom 2"
}
/* fmt.Println(<-myCh)
fmt.Println("Clear!") */
}()
go func() {
wq.Wait()
close(myCh)
fmt.Println("Closed myCH")
}()
for ch := range myCh {
fmt.Println("ch:", ch)
}
}