Class: Concurrent::Condition

Inherits:
Object
  • Object
show all
Defined in:
lib/concurrent/atomic/condition.rb

Overview

Condition is a better implementation of standard Ruby ConditionVariable. The biggest difference is the wait return value: Condition#wait returns Condition::Result which make possible to know if waiting thread has been woken up by an another thread (using #signal or #broadcast) or due to timeout.

Every #wait must be guarded by a locked Mutex or a ThreadError will be risen. Although it’s not mandatory, it’s recommended to call also #signal and #broadcast within the same mutex

Defined Under Namespace

Classes: Result

Instance Method Summary collapse

Constructor Details

#initializeCondition

Returns a new instance of Condition.



34
35
36
# File 'lib/concurrent/atomic/condition.rb', line 34

def initialize
  @condition = ConditionVariable.new
end

Instance Method Details

#broadcasttrue

Wakes up all waiting threads

Returns:

  • (true)


61
62
63
64
# File 'lib/concurrent/atomic/condition.rb', line 61

def broadcast
  @condition.broadcast
  true
end

#signaltrue

Wakes up a waiting thread

Returns:

  • (true)


54
55
56
57
# File 'lib/concurrent/atomic/condition.rb', line 54

def signal
  @condition.signal
  true
end

#wait(mutex, timeout = nil) ⇒ Result

Parameters:

  • mutex (Mutex)

    the locked mutex guarding the wait

  • timeout (Object) (defaults to: nil)

    nil means no timeout

Returns:



41
42
43
44
45
46
47
48
49
50
# File 'lib/concurrent/atomic/condition.rb', line 41

def wait(mutex, timeout = nil)
  start_time = Time.now.to_f
  @condition.wait(mutex, timeout)

  if timeout.nil?
    Result.new(nil)
  else
    Result.new(start_time + timeout - Time.now.to_f)
  end
end