Junior — Middle
Kas sa saad selgitada, mis on tingimusmuutuja sync.Cond Go keeles ja milleks seda kasutatakse?
sobes.tech AI
Vastus AI-lt
In the Go language, sync.Cond is a structure that implements a condition variable, used for synchronizing goroutines. It allows one or more goroutines to wait for a specific condition to be met and to notify other goroutines that this condition has changed.
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 of usage:
var mu sync.Mutex
cond := sync.NewCond(&mu)
// Goroutine waiting for a signal
go func() {
mu.Lock()
cond.Wait() // waiting for the signal
// after waking up, perform actions
mu.Unlock()
}()
// Goroutine sending the signal
mu.Lock()
cond.Signal() // wakes up one goroutine
mu.Unlock()
This way, sync.Cond helps coordinate the work of multiple goroutines waiting for certain conditions to be met.