Module: EventMachine::Synchrony

Defined in:
lib/em-synchrony.rb,
lib/em-synchrony/thread.rb,
lib/em-synchrony/em-multi.rb,
lib/em-synchrony/iterator.rb,
lib/em-synchrony/tcpsocket.rb,
lib/em-synchrony/connection_pool.rb

Defined Under Namespace

Modules: Thread Classes: ConnectionPool, Iterator, Multi, TCPSocket

Class Method Summary collapse

Class Method Details

.sleep(secs) ⇒ Object

a Fiber-aware sleep function using an EM timer



54
55
56
57
58
# File 'lib/em-synchrony.rb', line 54

def self.sleep( secs )
  fiber = Fiber.current
  EM::Timer.new(secs) {  fiber.resume  }
  Fiber.yield
end

.sync(df) ⇒ Object

sync is a close relative to inclineCallbacks from Twisted (Python)

Synchrony.sync allows you to write sequential code while using asynchronous or callback-based methods under the hood. Example:

result = EM::Synchrony.sync EventMachine::HttpRequest.new(URL).get p result.response

As long as the asynchronous function returns a Deferrable object, which has a “callback” and an “errback”, the sync methond will automatically yield and automatically resume your code (via Fibers) when the call either succeeds or fails. You do not need to patch or modify the Deferrable object, simply pass it to EM::Synchrony.sync



45
46
47
48
49
50
51
# File 'lib/em-synchrony.rb', line 45

def self.sync(df)
  f = Fiber.current
  df.callback { |r| f.resume(r) }
  df.errback { |r| f.resume(r) }

  Fiber.yield
end