Created
November 20, 2013 19:39
-
-
Save betawaffle/7569626 to your computer and use it in GitHub Desktop.
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
class WaitGroup | |
def initialize(initial_count = 0) | |
@count = initial_count | |
@cond = ConditionVariable.new | |
@mutex = Mutex.new | |
end | |
def add(delta = 1) | |
synchronize do | |
count = @count += 1 | |
broadcast if count <= 0 | |
count | |
end | |
end | |
def done? | |
@mutex.synchronize { @count <= 0 } | |
end | |
def remove(delta = 1) | |
add(-delta) | |
end | |
def wait | |
synchronize { sleep until @count <= 0 } | |
end | |
private | |
def broadcast | |
@cond.broadcast | |
end | |
def sleep | |
@cond.wait(@mutex) | |
end | |
def synchronize | |
@mutex.synchronize { yield } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment