Skip to content

Instantly share code, notes, and snippets.

@raroni
Created April 16, 2010 08:51
Show Gist options
  • Save raroni/368184 to your computer and use it in GitHub Desktop.
Save raroni/368184 to your computer and use it in GitHub Desktop.
Asynchronous IO behaving synchronously using Ruby 1.9's fibers
# 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
}
@raroni
Copy link
Author

raroni commented Apr 16, 2010

rasmus-rnn-nielsens-macbook-pro:ruby rasmus$ time ruby mysql_test.rb
Sending query...
Sending query...
Sending query...
Result: #Mysql::Result:0x00000100ae38d0
Result: #Mysql::Result:0x00000100ae3748
Result: #Mysql::Result:0x00000100ae3630

real 0m1.054s
user 0m0.035s
sys 0m0.016s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment