I'm learning Go. I'm trying to solve the deadlock issue on goroutines using semaphores. I have created two functions that write to an unbuffered channel. the reading is happening on the main channel. the third function is supposed to close the channel. when I run the program, it throws this error fatal error: all goroutines are asleep - deadlock! can somebody explain to me why this isn't working.
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
var s = []string{"a", "b", "c", "d"}
var w = []string{"w", "x", "t", "z", "p"}
func f(c chan string, ch chan bool) {
for _, word := range s {
c <- word
}
fmt.Println("f about to exit")
ch <- true
wg.Done()
}
func g(c chan string, ch chan bool) {
for _, word := range w {
c <- word
}
fmt.Println("g about to exit")
ch <- true
wg.Done()
}
func f1(ch chan string, c chan bool) {
<-c
<-c
fmt.Println("about to close channel")
close(ch)
}
func main() {
ch := make(chan string)
c := make(chan bool)
wg.Add(3)
go f(ch, c)
go g(ch, c)
go f1(ch, c)
for word := range ch {
fmt.Println(word)
}
wg.Wait()
}