Skip to content

Instantly share code, notes, and snippets.

@jrochkind
Created November 14, 2011 16:42
Show Gist options
  • Save jrochkind/1364397 to your computer and use it in GitHub Desktop.
Save jrochkind/1364397 to your computer and use it in GitHub Desktop.
test multi-threaded concurrency with activerecord adapters
# Adapted from slide 5 at http://www.slideshare.net/igrigorik/no-callbacks-no-threads-railsconf-2010
require 'rubygems'
require 'active_record'
require 'mysql'
gem 'mysql2', "< 0.3.0" # for rails 3.0
#gem 'mysql2', ">= 0.3.0" # for rails 3.1
ActiveRecord::Base.establish_connection(
:adapter => 'mysql2', # or 'mysql'
:host => '',
:database => '',
:username => '',
:password => '',
:pool => 5
)
stime = Time.now
threads = []
10.times do |n|
threads << Thread.new do
ActiveRecord::Base.connection_pool.with_connection do |conn|
res = conn.execute("sqlite3_sleep(1000)")
end
end
end
threads.each do |t|
begin
t.join
rescue Exception => e
puts "Exception in thread: #{e.class}"
end
end
puts "\n\nElapsed real time: #{Time.now - stime} seconds"
# On my computer:
#
# * mysql: 10.19 seconds, as expected for broken mysql adapter that holds onto
# ruby GIL
#
# * mysql2 with either ruby 1.8.7 OR ruby 1.9.2: 2.1 seconds
# (still surprisingly more than the 1s and change expected. still a lot of
# overhead from context switching and/or connection pool checkout?
# But not as disastrous as 'mysql'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment