Skip to content

Instantly share code, notes, and snippets.

@betawaffle
Created November 20, 2013 19:39
Show Gist options
  • Save betawaffle/7569626 to your computer and use it in GitHub Desktop.
Save betawaffle/7569626 to your computer and use it in GitHub Desktop.
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