class Thread::Monitor::ConditionVariable

Condition variables, allow to suspend the current thread while in the middle of a critical section until a condition is met, such as a resource being available.

Example:

  monitor = Thread::Monitor.new

  resource_available = false
  condvar = monitor.new_cond

  a1 = Thread.new {
    # Thread 'a1' waits for the resource to become available and consumes
    # the resource.
    monitor.synchronize {
      condvar.wait_until { resource_available }
      # After the loop, 'resource_available' is guaranteed to be true.

      resource_available = false
      puts "a1 consumed the resource"
    }
  }

  a2 = Thread.new {
    # Thread 'a2' behaves like 'a1'.
    monitor.synchronize {
      condvar.wait_until { resource_available }
      resource_available = false
      puts "a2 consumed the resource"
    }
  }

  b = Thread.new {
    # Thread 'b' periodically makes the resource available.
    loop {
      monitor.synchronize {
        resource_available = true

        # Notify one waiting thread if any.  It is possible that neither
        # 'a1' nor 'a2 is waiting on 'condvar' at this moment.  That's OK.
        condvar.signal
      }
      sleep 1
    }
  }

  # Eventually both 'a1' and 'a2' will have their resources, albeit in an
  # unspecified order.
  [a1, a2].each {|th| th.join}