ActiveRecord thread-safety

Hi,

I want to use ActiveRecord outside Rails. The application is
multithreaded, so database access has to be thread-safe. I read in a few
places ActiveRecord in fact should be thread-safe and I gave it a try,
but my findings indicate ActiveRecord is NOT thread-safe.
The following test-script fails every with a lost MySQL-connenction:

require ‘rubygems’
require_gem ‘activerecord’
require ‘models/user.rb’

ActiveRecord::Base.establish_connection(
:adapter => ‘mysql’, :host => ‘localhost’,
:database => ‘test’, :username => ‘test’
)

if (!User.find(:first))
User.create(:name => ‘dummy’, :password => ‘unsecure’)
end

threads = []

20.times do |i|
t = Thread.new do
User.find(:first)
end
threads.push(t)
end
threads.each { |t| t.join }

(to reproduce, replace the database and model with something present on
your system).
the error message:
Mysql::Error: Lost connection to MySQL server during query: …

if anybody could shed some light on how thread-safe ActiveRecord really
is it would be very much appreciated.

Thx,
Michael

On 7/7/06, Michael Bürge [email protected] wrote:

I want to use ActiveRecord outside Rails. The application is
multithreaded, so database access has to be thread-safe. I read in a few
places ActiveRecord in fact should be thread-safe and I gave it a try,
but my findings indicate ActiveRecord is NOT thread-safe.

Have you checked the value of ActiveRecord::Base.allow_concurrency is
set to true?

Tom

Wow, never have seen that before!

It’s not even in the apidocs (http://api.rubyonrails.org/) but exists…

It there a more accurate documentation sneaking around somewhere?! :slight_smile:

regards
Peter

Tom W. schrieb:

Have you checked the value of ActiveRecord::Base.allow_concurrency is
set to true?

No I didn’t! …didn’t know it existed.
It was set to false and when set to true my test works as desired.

That was the missing piece of information needed, thank you very much!

I guess I will look at the sources more from now on after unsuccessful
searches for documentation/explanation :wink:

Michael