1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
# =XMPP4R - XMPP Library for Ruby
# License:: Ruby's license (see the LICENSE file) or GNU GPL, at your option.
# Website::http://xmpp4r.github.io
module Jabber
##
# This class implements semaphore for threads synchronization.
class Semaphore
##
# Initialize new semaphore
#
# val:: [Integer] number of threads, that can enter to section
def initialize(val=0)
@tickets = val
@lock = Mutex.new
@cond = ConditionVariable.new
end
##
# Waits until are available some free tickets
def wait
@lock.synchronize {
@cond.wait(@lock) while !(@tickets > 0)
@tickets -= 1
}
end
##
# Unlocks guarded section, increments number of free tickets
def run
@lock.synchronize {
@tickets += 1
@cond.signal
}
end
end
end
|