Class: Ori::Semaphore

Inherits:
Object
  • Object
show all
Includes:
Selectable
Defined in:
lib/ori/semaphore.rb

Direct Known Subclasses

Mutex

Instance Method Summary collapse

Constructor Details

#initialize(num_tickets) ⇒ Semaphore

Returns a new instance of Semaphore.

Raises:

  • (ArgumentError)


7
8
9
10
11
12
# File 'lib/ori/semaphore.rb', line 7

def initialize(num_tickets)
  raise ArgumentError, "Number of tickets must be positive" if num_tickets <= 0

  @tickets = num_tickets
  @available = num_tickets
end

Instance Method Details

#acquireObject



30
31
32
33
34
# File 'lib/ori/semaphore.rb', line 30

def acquire
  Fiber.yield(self) until available?
  @available -= 1
  true
end

#available?Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/ori/semaphore.rb', line 36

def available?
  @available > 0
end

#awaitObject



44
45
46
47
# File 'lib/ori/semaphore.rb', line 44

def await
  Fiber.yield until available?
  true
end

#countObject



40
41
42
# File 'lib/ori/semaphore.rb', line 40

def count
  @available
end

#releaseObject



23
24
25
26
27
28
# File 'lib/ori/semaphore.rb', line 23

def release
  raise "Semaphore overflow" if @available >= @tickets

  @available += 1
  true
end

#syncObject



14
15
16
17
18
19
20
21
# File 'lib/ori/semaphore.rb', line 14

def sync
  acquire
  begin
    yield
  ensure
    release
  end
end