Last active
March 5, 2021 02:23
-
-
Save oprypin/9915def54564a7c44d53f15eaa1ab9b6 to your computer and use it in GitHub Desktop.
Crystal parallel jobs from an array
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
def paralleln(items : Indexable(T), &block : T -> R) forall T, R | |
results = Array(R).new(items.size) { r = uninitialized R } | |
done = Channel(Exception?).new | |
items.each_with_index do |item, i| | |
spawn do | |
begin | |
results[i] = block.call(item) | |
rescue e | |
done.send e | |
else | |
done.send nil | |
end | |
end | |
end | |
items.each do | |
if (exc = done.receive) | |
raise exc | |
end | |
end | |
results | |
end | |
require "http/client" | |
urls = ["https://example.com/", "https://crystal-lang.org"] | |
pages = paralleln(urls) do |url| | |
HTTP::Client.get(url) | |
end | |
p pages |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment