Unable to understand this dead lock situation in golang, i have below to go code with pub and sub pattern
package main
import (
"fmt"
"sync"
)
func main() {
cond := sync.NewCond(&sync.Mutex{})
subscribe := func(c *sync.Cond, fn func()) {
var goroutineRunning sync.WaitGroup
goroutineRunning.Add(1)
go func() {
goroutineRunning.Done()
fmt.Println("waiting")
c.L.Lock()
c.Wait()
c.L.Unlock()
fn()
}()
goroutineRunning.Wait()
}
var clickRegistered sync.WaitGroup
clickRegistered.Add(2)
subscribe(cond, func() {
fmt.Println("notified 1")
clickRegistered.Done()
})
subscribe(cond, func() {
fmt.Println("notified 2")
clickRegistered.Done()
})
cond.Broadcast()
clickRegistered.Wait()
}
I couldn't able to understand, why i am getting dead lock if i put fmt.Println("waiting")
after goroutineRunning.Done()
, if i remove the fmt.Println("waiting")
or move above goroutineRunning.Done()
its working as expected, why it is happening like this?
Need to run go run main.go multiple times to get the dead lock it may work at first time.