Sobes.tech
Middle

How does the conditional variable (sync.Cond) work in Go?

sobes.tech AI

Answer from AI

In Go, sync.Cond is a condition variable used for coordinating goroutines, allowing one or more goroutines to wait for a certain condition to occur.

Main methods:

  • Wait(): blocks the current goroutine and releases the associated mutex until Signal() or Broadcast() is called.
  • 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 that waits for the condition
go func() {
    mu.Lock()
    cond.Wait() // wait for signal
    // condition met
    mu.Unlock()
}()

// Goroutine that signals
mu.Lock()
// change state that the first goroutine is waiting for
cond.Signal() // or cond.Broadcast()
mu.Unlock()

It is important that Wait() is called with the mutex locked, and when Wait() is called, the mutex is temporarily released so that other goroutines can change the state and call Signal() or Broadcast(). After waking up, Wait() locks the mutex again before returning.

Thus, sync.Cond allows efficient synchronization of goroutines based on state changes.

How does the conditional variable (sync.Cond) work in… - sobes.tech