Skip to content

Instantly share code, notes, and snippets.

@oprypin
Last active March 5, 2021 02:23
Show Gist options
  • Select an option

  • Save oprypin/9915def54564a7c44d53f15eaa1ab9b6 to your computer and use it in GitHub Desktop.

Select an option

Save oprypin/9915def54564a7c44d53f15eaa1ab9b6 to your computer and use it in GitHub Desktop.

Revisions

  1. oprypin revised this gist May 3, 2018. 1 changed file with 3 additions and 2 deletions.
    5 changes: 3 additions & 2 deletions parraleln.cr
    Original file line number Diff line number Diff line change
    @@ -26,7 +26,8 @@ end

    require "http/client"

    pages = paralleln(["https://example.com/", "https://crystal-lang.org"]) { |url|
    urls = ["https://example.com/", "https://crystal-lang.org"]
    pages = paralleln(urls) do |url|
    HTTP::Client.get(url)
    }
    end
    p pages
  2. oprypin revised this gist May 3, 2018. 1 changed file with 8 additions and 4 deletions.
    12 changes: 8 additions & 4 deletions parraleln.cr
    Original file line number Diff line number Diff line change
    @@ -1,19 +1,23 @@
    def paralleln(items : Indexable(T), &block : T -> R) forall T, R
    results = Array(R).new(items.size) { r = uninitialized R }
    done = Channel(Nil).new
    done = Channel(Exception?).new

    items.each_with_index do |item, i|
    spawn do
    begin
    results[i] = block.call(item)
    ensure
    rescue e
    done.send e
    else
    done.send nil
    end
    end
    end

    items.size.times do
    done.receive
    items.each do
    if (exc = done.receive)
    raise exc
    end
    end

    results
  3. oprypin revised this gist May 3, 2018. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion parraleln.cr
    Original file line number Diff line number Diff line change
    @@ -13,7 +13,7 @@ def paralleln(items : Indexable(T), &block : T -> R) forall T, R
    end

    items.size.times do
    done.receive
    done.receive
    end

    results
  4. oprypin created this gist May 3, 2018.
    28 changes: 28 additions & 0 deletions parraleln.cr
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    def paralleln(items : Indexable(T), &block : T -> R) forall T, R
    results = Array(R).new(items.size) { r = uninitialized R }
    done = Channel(Nil).new

    items.each_with_index do |item, i|
    spawn do
    begin
    results[i] = block.call(item)
    ensure
    done.send nil
    end
    end
    end

    items.size.times do
    done.receive
    end

    results
    end


    require "http/client"

    pages = paralleln(["https://example.com/", "https://crystal-lang.org"]) { |url|
    HTTP::Client.get(url)
    }
    p pages