A
A
Alexey Verkhovtsev2020-11-04 19:18:34
go
Alexey Verkhovtsev, 2020-11-04 19:18:34

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()


This line fmt.Println("I'm created") is never called... I found examples of other examples in books, but they are all different and I can't understand the process itself. In theory, I'm waiting for a signal in the goroutine, at the end I send it and the goroutine should be unblocked, but somehow it doesn't work (. If I put wg.Done at the end, then I generally get a deadlock

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Samsonov, 2020-11-04
@seftomsk

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()

https://play.golang.org/p/fuSnDNTGYeZ
sync.Cond allows you to synchronize goroutines on events, replace an endless loop of waiting for some specific condition. This is useful, for example, if we want to unblock several goroutines at once (Broadcast), which cannot be done using a channel. The Signal method sends a message to the longest waiting goroutine

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question