Sobes.tech
Junior — Middle

Explain what a conditional variable is and how it is used for thread synchronization.

sobes.tech AI

Answer from AI

A condition variable is a synchronization mechanism that allows one or more threads to wait until a certain condition is met, while another thread notifies them of a change in state.

In Go, condition variables are implemented using the sync.Cond type. It works together with a mutex (sync.Mutex), which protects shared data. A thread that wants to wait calls Wait(), which releases the mutex and blocks until another thread calls Signal() (to wake up one thread) or Broadcast() (to wake up all waiting threads).

Example usage:

var mu sync.Mutex
cond := sync.NewCond(&mu)
sharedDataReady := false

// Thread that waits
mu.Lock()
for !sharedDataReady {
    cond.Wait() // releases mu and waits for a signal
}
// Here, sharedDataReady == true
mu.Unlock()

// Thread that changes the state
mu.Lock()
sharedDataReady = true
cond.Signal() // or cond.Broadcast() to wake all waiting threads
mu.Unlock()

Thus, a condition variable helps organize correct waiting and notification between threads, avoiding active polling and data races.