Skip to content

Instantly share code, notes, and snippets.

@axelabs
Created March 19, 2015 15:34

Revisions

  1. axelabs created this gist Mar 19, 2015.
    37 changes: 37 additions & 0 deletions em-dc-unblock.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    #!/usr/bin/ruby

    # Example of how to unblock EventMachine's deffered callbacks
    # Based on http://stackoverflow.com/a/11778588/632827
    # For output example see: http://goo.gl/d6E9E0

    require 'eventmachine'

    iam = [ 'blocking', 'non-blocking' ]

    def unBlock &blocking
    proc { EM.defer(blocking) }
    end

    work = proc {
    puts "[#{Time.now}] I'm a blocking worker, I'll be done in 2 secs"
    sleep 2
    puts "[#{Time.now}] worker done!"
    }

    callback = proc {
    puts "[#{Time.now}] I'm a %s callback, I'll be done in 4 secs" % iam.shift
    sleep 4
    puts "[#{Time.now}] callback done!"
    }

    EM.run do
    EM.add_periodic_timer(1) { puts "[#{Time.now}] ." }

    EM.defer(work, callback )
    # Lets do the same thing in a bit but unblocked
    EM.add_timer(7) {
    EM.defer(work, unBlock {callback.call} )
    }

    EM.add_timer(15) { puts "[#{Time.now}] Bye!"; EM.stop }
    end