Created
April 27, 2010 12:17
-
-
Save rubyworks/380677 to your computer and use it in GitHub Desktop.
semaphore.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# = Semaphore | |
# | |
# Technically a semaphore is simply an integer variable which | |
# has an execution queue associated with it. | |
# | |
# Copyright (c) 2005 Fukumoto | |
class Semaphore | |
def initialize(initvalue = 0) | |
@counter = initvalue | |
@waiting_list = [] | |
end | |
def wait | |
Thread.critical = true | |
if (@counter -= 1) < 0 | |
@waiting_list.push(Thread.current) | |
Thread.stop | |
end | |
self | |
ensure | |
Thread.critical = false | |
end | |
def signal | |
Thread.critical = true | |
begin | |
if (@counter += 1) <= 0 | |
t = @waiting_list.shift | |
t.wakeup if t | |
end | |
rescue ThreadError | |
retry | |
end | |
self | |
ensure | |
Thread.critical = false | |
end | |
alias_method( :down, :wait ) | |
alias_method( :up, :signal ) | |
alias_method( :p, :wait ) | |
alias_method( :v, :signal ) | |
def exclusive | |
wait | |
yield | |
ensure | |
signal | |
end | |
alias_method( :synchronize, :exclusive ) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment