Class: Rbgo::Semaphore

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

Instance Method Summary collapse

Constructor Details

#initialize(count) ⇒ Semaphore

Returns a new instance of Semaphore.



3
4
5
6
7
8
9
# File 'lib/rbgo/semaphore.rb', line 3

def initialize(count)
  count = count.to_i
  raise 'count must be positive' if count <= 0
  @mutex = Mutex.new
  @cond  = ConditionVariable.new
  @count = count
end

Instance Method Details

#acquire(permits = 1) ⇒ Object



17
18
19
20
21
22
23
24
25
26
# File 'lib/rbgo/semaphore.rb', line 17

def acquire(permits = 1)
  raise 'Must be called with a block' unless block_given?

  begin
   ok = _acquire(permits)
    yield
  ensure
    release(permits) if ok
  end
end

#acquire_allObject



28
29
30
31
32
33
34
35
36
37
# File 'lib/rbgo/semaphore.rb', line 28

def acquire_all
  raise 'Must be called with a block' unless block_given?

  begin
    permits = drain_permits
    yield
  ensure
    release(permits)
  end
end

#available_permitsObject



11
12
13
14
15
# File 'lib/rbgo/semaphore.rb', line 11

def available_permits
  @mutex.synchronize do
    return @count
  end
end

#release(permits = 1) ⇒ Object



51
52
53
54
55
56
57
58
59
# File 'lib/rbgo/semaphore.rb', line 51

def release(permits = 1)
  permits = permits.to_i
  raise 'permits must be positive' if permits <= 0
  @mutex.synchronize do
    @count += permits
    @cond.broadcast
  end
  self
end

#try_acquire(permits = 1) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rbgo/semaphore.rb', line 39

def try_acquire(permits = 1)
  raise 'Must be called with a block' unless block_given?

  begin
    ok = _try_acquire(permits)
    yield if ok
  ensure
    release(permits) if ok
  end
  return ok
end