Skip to content

Instantly share code, notes, and snippets.

@jamonholmgren
Created May 13, 2015 21:13
Show Gist options
  • Select an option

  • Save jamonholmgren/3a37a5d7695ac7e0bd9b to your computer and use it in GitHub Desktop.

Select an option

Save jamonholmgren/3a37a5d7695ac7e0bd9b to your computer and use it in GitHub Desktop.

Revisions

  1. jamonholmgren created this gist May 13, 2015.
    33 changes: 33 additions & 0 deletions app_delegate.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@

    class AppDelegate
    include Async

    def application(application, didFinishLaunchingWithOptions:launchOptions)

    thread_1 = async do
    i = 0
    300_000.times do
    sleep 0.000001
    i += (300_000 - i)
    end
    main { puts i }
    end

    thread_2 = async do
    i = 0
    900_000.times do
    sleep 0.000001
    i += (900_000 - i)
    end
    main { puts i }
    end

    after thread_1, thread_2 do
    puts "They're both done."
    end

    true
    end
    end


    40 changes: 40 additions & 0 deletions rm-async.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    module Async
    def async(&callback)
    GroupAsync.new.async(&callback)
    end

    def main(&callback)
    Dispatch::Queue.main.async(&callback)
    end

    def after(*asyncs, &callback)
    async do
    asyncs.each{|a| a.group.wait }
    callback.call
    end
    end

    class GroupAsync
    attr_reader :group

    def initialize
    @group = Dispatch::Group.new
    end

    def async(&callback)
    Dispatch::Queue.concurrent.async(group) do
    callback.call
    end
    self
    end
    alias_method :and, :async

    def then(&callback)
    Dispatch::Queue.concurrent.async do
    group.wait
    callback.call
    end
    self
    end
    end
    end