Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Rails 3 cattr_accessor thread-safe?

Is Rails 3 cattr_accessor thread-safe?

like image 376
Anh Nguyen Avatar asked Feb 14 '12 10:02

Anh Nguyen


People also ask

Is Rails thread-safe?

Rails and its included gems have been declared thread-safe since 2.2, i.e. since 2008. This alone, however, does not automatically make your app as a whole so. Your own app code and all the gems you use need to be thread-safe as well.

Are Ruby arrays thread-safe?

In standard Ruby implementations, an Array is not thread-safe.

Are instance variables thread-safe in Ruby?

Performing writes/reads on class variables in Ruby is not thread safe. Performing writes/reads on instance variables appears to be thread safe.


1 Answers

No, it's not. Just get a quick look at the cattr_reader code:

# File activesupport/lib/active_support/core_ext/class/attribute_accessors.rb, line 28
def cattr_reader(*syms)
  options = syms.extract_options!
  syms.each do |sym|
    class_eval(        unless defined? @@#{sym}          @@#{sym} = nil        end        def self.#{sym}          @@#{sym}        end, __FILE__, __LINE__ + 1)

    unless options[:instance_reader] == false
    class_eval(          def #{sym}            @@#{sym}          end, __FILE__, __LINE__ + 1)
    end
  end
end

And you could run simple test:

class A
  cattr_accessor :b
end

t1 = Thread.new { A.b = 1;  sleep 1; p (A.b == 1); }
t2 = Thread.new { A.b = 2 }
t1.join
t2.join
# outputs "false"

Here is a way to make it work thread-safely: http://rails-bestpractices.com/posts/2010/08/23/fetch-current-user-in-models/

like image 50
icanhazbroccoli Avatar answered Sep 28 '22 07:09

icanhazbroccoli