Skip to content

Instantly share code, notes, and snippets.

@vidarh
Last active December 4, 2024 09:02
Show Gist options
  • Save vidarh/6216b9438ee2966bb63ca4c4254ccbd0 to your computer and use it in GitHub Desktop.
Save vidarh/6216b9438ee2966bb63ca4c4254ccbd0 to your computer and use it in GitHub Desktop.
Example Ruby M:N threading
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