How does sync.Cond method wait() work?

Look at this code:

	c.L.Lock()
	for i <= 99 {
		c.Wait()
	}
	c.L.Unlock()

At some point, between the c.L.Lock() command and the c.Wait() instruction, some other goroutine will call c.Signal() or c.Broadcast().

What happens with c.Wait() if just before it some other goroutine issued c.Signal() or c.Broadcast() before … what will happen with this c.Wait() ? Will it wait forever, will somehow the previously issued c.Signal() be somehow remembered like in a channel ?

If one goroutine calls cond.Wait() after another goroutine has called cond.Signal(), then it will not wake up. cond.Signal() will only notify one of the goroutines that have already called cond.Wait() before it runs. If you call both “at the same time”, the goroutine calling Wait() might get a chance to add itself to the wait list, but there are no guarantees around that. If many goroutines call Wait(), the implementation is such that they are woken up in order, but note that that behavior is not part of the API. There are no channels involved.

1 Like

Thx! I suspected that Signal() and Broadcast() would be lost if they occur just before a call to Wait().

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.