Skip to content

Instantly share code, notes, and snippets.

@ncr
Forked from raroni/async_io_looking_sync.rb
Created April 22, 2010 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ncr/375854 to your computer and use it in GitHub Desktop.
Save ncr/375854 to your computer and use it in GitHub Desktop.
# this code snippet was inspired by
# http://www.igvita.com/2010/04/15/non-blocking-activerecord-rails/
require 'fiber' # needed to use Fiber.current
require 'rubygems'
require 'mysqlplus'
require 'eventmachine'
require 'em-mysqlplus'
def query(sql)
con = EventMachine::MySQL.new(:host => 'localhost')
f = Fiber.current
r = con.query sql
r.callback { |res|
f.resume res
}
Fiber.yield
end
EM.run {
count = 0
3.times do
Fiber.new {
puts "Sending query..."
result = query('SELECT SLEEP(1)')
puts "Result: #{result}"
count += 1
EM.stop if count == 3
}.resume
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment