Created
July 11, 2013 00:05
-
-
Save dgrijalva/5971354 to your computer and use it in GitHub Desktop.
Wait Group in ruby using ConditionVariable
This file contains 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
require 'thread' | |
class WaitGroup | |
def initialize | |
@count = 0 | |
@done = false | |
@cond = ConditionVariable.new | |
@lock = Mutex.new | |
end | |
def add n = 1 | |
@lock.synchronize do | |
@count += n | |
end | |
end | |
def done n = 1 | |
@lock.synchronize do | |
@count -= n | |
if @count == 0 | |
@done = true | |
@cond.broadcast | |
end | |
end | |
end | |
def wait | |
@lock.synchronize do | |
while !@done | |
@cond.wait(@lock) | |
end | |
end | |
end | |
end | |
wg = WaitGroup.new | |
wg.add 3 | |
3.times do | |
Thread.new { | |
t = rand(10000) / 10000.0 | |
puts "sleeping for #{t}\n" | |
sleep(t) | |
puts "done\n" | |
wg.done | |
} | |
end | |
wg.wait | |
puts "YAY!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You know, for kids!