问题
My Rails 3.1 app uses an engine and I want to know if access to this engine is threadsafe.
I have /lib/mymodule.rb in the engine and it looks something like this:
module MyModule
def self.my_method()
begin
data = WebResource.find(:all) # Where WebResource < ActiveResource::Base
rescue
data = nil
end
return data
end
end
Then in my views/controllers, I call this method like this:
MyModule::WebResource.headers[:some_id] = cookies[:some_id]
MyModule::my_method()
In my main app, I have the threadsafe! configuration option set. I know that with threadsafe! enabled, each Controller lives in it's own thread for each request.
However, is this Module threadsafe? I suspect that there is only one copy of this module for all requests, so it is not inherently thread safe, and requires manual synchronization using something like a Mutex. Specifically, I have code that sets the header for the HTTP request outside of the ActiveResource class WebResource
. Could this cause a threading issue?
回答1:
It will depend on what you do inside this method as to whether it is thread safe. If it touches no class variables, then it is thread safe.
If it stores or sets information at the class level and assumes that no other method is going to touch that information before it uses it again, then it is not thread safe.
来源:https://stackoverflow.com/questions/12484221/rails-engine-thread-safety-activeresource