Created
February 18, 2021 15:20
-
-
Save mweitzel/c80a93af2b05ad22f2c50b39b709c23f to your computer and use it in GitHub Desktop.
Ruby WaitGroup without a mutex, using ractors.
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
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