Class: Concurrent::Selectable::Semaphore

Inherits:
Base
  • Object
show all
Defined in:
lib/concurrent/selectable/semaphore.rb

Overview

A Semaphore is a counter which can be atomically incremented and decremented; attempts to decrement the counter below zero will block.

Instance Method Summary collapse

Methods inherited from Base

#close, #to_io

Constructor Details

#initialize(count = 0) ⇒ Semaphore

Creates a semaphore with the given initial count



45
46
47
48
49
# File 'lib/concurrent/selectable/semaphore.rb', line 45

def initialize(count=0)
  super()
  @lock = ::Mutex.new
  @count = count
end

Instance Method Details

#exclusiveObject Also known as: synchronize



82
83
84
85
86
87
88
89
# File 'lib/concurrent/selectable/semaphore.rb', line 82

def exclusive
  wait
  begin
    yield
  ensure
    signal
  end
end

#nonzero?Boolean

Returns true if the count is currently nonzero (additional external synchronization is usually required if other threads can modify the semaphore)

Returns:

  • (Boolean)


102
103
104
# File 'lib/concurrent/selectable/semaphore.rb', line 102

def nonzero?
  @lock.synchronize { @count.nonzero? }
end

#signalObject Also known as: put, up, v

Increments the semaphore



52
53
54
55
56
57
58
# File 'lib/concurrent/selectable/semaphore.rb', line 52

def signal
  @lock.synchronize do
    internal_set if @count.zero?
    @count += 1
  end
  self
end

#wait(blocking = true) ⇒ Object Also known as: get, down, p

Decrements the semaphore, blocking if its count is already zero and blocking is true.



65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/concurrent/selectable/semaphore.rb', line 65

def wait(blocking=true)
  loop do
    @lock.synchronize do
      if @count.nonzero?
        @count -= 1
        internal_reset if @count.zero?
        return self
      end
    end
    return nil unless blocking
    super()
  end
end

#zero?Boolean

Returns true if the count is currently zero (additional external synchronization is usually required if other threads can modify the semaphore)

Returns:

  • (Boolean)


95
96
97
# File 'lib/concurrent/selectable/semaphore.rb', line 95

def zero?
  @lock.synchronize { @count.zero? }
end