Class: RubyReactor::Semaphore

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_reactor/semaphore.rb

Defined Under Namespace

Classes: AcquisitionError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, limit: 1, wait: 0) ⇒ Semaphore

Returns a new instance of Semaphore.



9
10
11
12
13
14
# File 'lib/ruby_reactor/semaphore.rb', line 9

def initialize(key, limit: 1, wait: 0)
  @key = "semaphore:#{key}"
  @limit = limit
  @wait = wait
  @token = nil
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



7
8
9
# File 'lib/ruby_reactor/semaphore.rb', line 7

def key
  @key
end

#limitObject (readonly)

Returns the value of attribute limit.



7
8
9
# File 'lib/ruby_reactor/semaphore.rb', line 7

def limit
  @limit
end

#tokenObject (readonly)

Returns the value of attribute token.



7
8
9
# File 'lib/ruby_reactor/semaphore.rb', line 7

def token
  @token
end

#waitObject (readonly)

Returns the value of attribute wait.



7
8
9
# File 'lib/ruby_reactor/semaphore.rb', line 7

def wait
  @wait
end

Instance Method Details

#acquireObject

rubocop:disable Naming/PredicateMethod

Raises:



16
17
18
19
20
21
22
23
24
# File 'lib/ruby_reactor/semaphore.rb', line 16

def acquire # rubocop:disable Naming/PredicateMethod
  ensure_initialized

  token = adapter.semaphore_acquire(@key, timeout: @wait)
  raise AcquisitionError, "Could not acquire semaphore '#{@key}' within #{@wait} seconds" unless token

  @token = token
  true
end

#releaseObject

Returns true if a held token was returned to the pool. Idempotent: a second release (or one without a prior acquire) is a no-op.



28
29
30
31
32
33
34
# File 'lib/ruby_reactor/semaphore.rb', line 28

def release
  return false unless @token

  result = adapter.semaphore_release(@key, @token, @limit)
  @token = nil
  result
end

#synchronizeObject



36
37
38
39
40
41
# File 'lib/ruby_reactor/semaphore.rb', line 36

def synchronize
  acquire
  yield
ensure
  release
end