我的用户模型有一个讨厌的方法,不应该同时为同一记录的两个实例调用.我需要连续执行两个http请求,同时确保任何其他线程不会同时为同一记录执行相同的方法.
class User ... def nasty_long_running_method // something nasty will happen if this method is called simultaneously // for two instances of the same record and the later one finishes http_request_1 // before the first one finishes http_request_2. http_request_1 // Takes 1-3 seconds. http_request_2 // Takes 1-3 seconds. update_model end end
例如,这会破坏一切:
user = User.first Thread.new { user.nasty_long_running_method } Thread.new { user.nasty_long_running_method }
但这没关系,应该允许:
user1 = User.find(1) user2 = User.find(2) Thread.new { user1.nasty_long_running_method } Thread.new { user2.nasty_long_running_method }