Class: Jabber::Semaphore

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

Overview

This class implements semaphore for threads synchronization.

Instance Method Summary collapse

Constructor Details

#initialize(val = 0) ⇒ Semaphore

Initialize new semaphore

val
Integer

number of threads, that can enter to section



14
15
16
17
18
# File 'lib/vendor/xmpp4r/lib/xmpp4r/semaphore.rb', line 14

def initialize(val=0)
  @tickets = val
  @lock = Mutex.new
  @cond = ConditionVariable.new
end

Instance Method Details

#runObject

Unlocks guarded section, increments number of free tickets



31
32
33
34
35
36
# File 'lib/vendor/xmpp4r/lib/xmpp4r/semaphore.rb', line 31

def run
  @lock.synchronize {
    @tickets += 1
    @cond.signal
  }
end

#waitObject

Waits until are available some free tickets



22
23
24
25
26
27
# File 'lib/vendor/xmpp4r/lib/xmpp4r/semaphore.rb', line 22

def wait
  @lock.synchronize {
    @cond.wait(@lock) while !(@tickets > 0)
    @tickets -= 1
  }
end