Junior — Middle
Can you explain what a conditional variable sync.Cond in Go language is and what it is used for?
sobes.tech AI
Answer from AI
In Go language, sync.Cond is a structure that implements a condition variable used for goroutine synchronization. It allows one or more goroutines to wait for a certain condition to become true and to notify other goroutines when this condition changes.
Main methods of sync.Cond:
Wait()— blocks the current goroutine until another goroutine callsSignal()orBroadcast().Signal()— wakes up one goroutine waiting on the condition variable.Broadcast()— wakes up all goroutines waiting on the condition variable.
Example usage:
var mu sync.Mutex
cond := sync.NewCond(&mu)
// Goroutine waiting for a signal
go func() {
mu.Lock()
cond.Wait() // wait for the signal
// perform actions after waking up
mu.Unlock()
}()
// Goroutine sending a signal
mu.Lock()
cond.Signal() // wake up one goroutine
mu.Unlock()
Thus, sync.Cond helps coordinate the work of multiple goroutines waiting for certain conditions to be met.