Last active
December 4, 2024 09:02
-
-
Save vidarh/6216b9438ee2966bb63ca4c4254ccbd0 to your computer and use it in GitHub Desktop.
Example Ruby M:N threading
This file contains hidden or 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
M = 4 | |
Result = Data.define(:idx, :val) | |
def gather(funcs) | |
ready = Queue.new | |
funcs.each_with_index {|val,idx| ready << Result.new(val:, idx:) } | |
result = [] | |
(0..M).map do | |
Thread.new do | |
begin | |
while job = ready.pop(true) | |
result[job.idx] = job.val.() | |
end | |
rescue ThreadError | |
# queue empty | |
end | |
end | |
end.map(&:join).map(&:value).flatten | |
result | |
end | |
funcs = (1..10).map {|i| | |
-> { "Value #{i}" } | |
} | |
p gather(funcs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment