Is Rails 3 cattr_accessor 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.
In standard Ruby implementations, an Array is not thread-safe.
Performing writes/reads on class variables in Ruby is not thread safe. Performing writes/reads on instance variables appears to be thread safe.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With