Junior — Middle
Selgitage, mis on tingimusmuutuja ja kuidas seda kasutatakse niitide sünkroniseerimiseks.
sobes.tech AI
Vastus AI-lt
A condition variable is a synchronization mechanism that allows one or more threads to wait for a certain condition to become true, while another thread notifies them of a change in state.
In Go, condition variables are implemented via the sync.Cond type. It works together with a mutex (sync.Mutex), which protects shared data. The waiting thread calls Wait(), which releases the mutex and blocks until another thread calls Signal() (to wake one thread) or Broadcast() (to wake all waiting threads).
Example usage:
var mu sync.Mutex
cond := sync.NewCond(&mu)
sharedDataReady := false
// Waiting thread
mu.Lock()
for !sharedDataReady {
cond.Wait() // releases mu and waits for signal
}
// sharedDataReady == true here
mu.Unlock()
// Thread that changes the state
mu.Lock()
sharedDataReady = true
cond.Signal() // or cond.Broadcast(), to wake waiting threads
mu.Unlock()
This way, the condition variable helps organize correct waiting and notification between threads, avoiding active polling and race conditions.