Skip to content

Instantly share code, notes, and snippets.

@dgrijalva
Created July 11, 2013 00:05
Show Gist options
  • Save dgrijalva/5971354 to your computer and use it in GitHub Desktop.
Save dgrijalva/5971354 to your computer and use it in GitHub Desktop.
Wait Group in ruby using ConditionVariable
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!"
@dgrijalva
Copy link
Author

You know, for kids!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment