Answer the question
In order to leave comments, you need to log in
How to understand how sync.Cond works in golang?
Hello everyone, I'm trying to understand how sync.Cond works. But something doesn't work, my example
c := sync.NewCond(&sync.Mutex{})
var wg sync.WaitGroup
wg.Add(1)
go func() {
wg.Done()
c.L.Lock()
defer c.L.Unlock()
c.Wait()
fmt.Println("I'm created")
}()
c.Signal()
wg.Wait()
Answer the question
In order to leave comments, you need to log in
The first mistake is calling wg.Done right at the start of the function. wg.Done() must be called before completion. The second mistake is assuming that when we call c.Signal() we have already reached c.Wait().
c := sync.NewCond(&sync.Mutex{})
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
c.L.Lock()
defer c.L.Unlock()
c.Wait()
fmt.Println("I'm created")
}()
time.Sleep(1 * time.Second)
c.Signal()
wg.Wait()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question