Created
April 16, 2010 08:51
-
-
Save raroni/368184 to your computer and use it in GitHub Desktop.
Asynchronous IO behaving synchronously using Ruby 1.9's fibers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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
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