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

#to_io, #wait

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

#get(blocking = true) ⇒ Object

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



53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/concurrent/selectable/semaphore.rb', line 53

def get(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
    wait
  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)


85
86
87
# File 'lib/concurrent/selectable/semaphore.rb', line 85

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

#putObject

Increments the semaphore



68
69
70
71
72
73
# File 'lib/concurrent/selectable/semaphore.rb', line 68

def put
  @lock.synchronize do
    internal_set if @count.zero?
    @count += 1
  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)


78
79
80
# File 'lib/concurrent/selectable/semaphore.rb', line 78

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