Skip to content

Instantly share code, notes, and snippets.

@mweitzel
Created February 18, 2021 15:20
Show Gist options
  • Save mweitzel/c80a93af2b05ad22f2c50b39b709c23f to your computer and use it in GitHub Desktop.
Save mweitzel/c80a93af2b05ad22f2c50b39b709c23f to your computer and use it in GitHub Desktop.
Ruby WaitGroup without a mutex, using ractors.
class WaitGroup
def initialize
@group = Ractor.new {
Ractor.yield("open")
count = 0
count += receive
while count > 0
count += receive
end
Ractor.yield("close")
}
end
def add(i=1)
@group.send(i)
self
end
def done
@group.send(-1)
self
end
def wait
@group.take
@group.send(0)
@group.take
end
end
wg = WaitGroup.new
Ractor.new(wg.add) { |wg| sleep 0.2; puts 'job a'; wg.done}
Ractor.new(wg.add) { |wg| sleep 0.3; puts 'job b'; wg.done}
Ractor.new(wg.add) { |wg| sleep 0.1; puts 'job c'; wg.done}
wg.wait
puts 'done'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment