Class: ProcessShared::ConditionVariable

Inherits:
Object
  • Object
show all
Defined in:
lib/process_shared/condition_variable.rb

Instance Method Summary collapse

Constructor Details

#initializeConditionVariable

Returns a new instance of ConditionVariable



5
6
7
8
9
10
# File 'lib/process_shared/condition_variable.rb', line 5

def initialize
  @internal = Semaphore.new(1)
  @waiting = SharedMemory.new(:int)
  @waiting.write_int(0)
  @sem = Semaphore.new(0)
end

Instance Method Details

#broadcastObject



12
13
14
15
16
# File 'lib/process_shared/condition_variable.rb', line 12

def broadcast
  @internal.synchronize do
    @waiting.read_int.times { @sem.post }
  end
end

#signalObject



18
19
20
21
22
# File 'lib/process_shared/condition_variable.rb', line 18

def signal
  @internal.synchronize do
    @sem.post unless @waiting.read_int.zero?
  end
end

#wait(mutex, timeout = nil) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/process_shared/condition_variable.rb', line 24

def wait(mutex, timeout = nil)
  mutex.unlock
  begin
    inc_waiting
    if timeout
      begin
        @sem.try_wait(timeout)
      rescue Errno::EAGAIN, Errno::ETIMEDOUT
        # success!
      end
    else
      @sem.wait
    end
    dec_waiting
  ensure
    mutex.lock
  end
end