Ruby多线程Sql(在测试环境中)

时间:2016-04-05 16:22:04

标签: ruby-on-rails ruby multithreading

我的测试在不同的线程中运行一些SQL查询时遇到问题。我希望在SQL中运行简单的select和count会返回相同的结果,但是如果我在线程(process_new_followersprocess_lost_followers)中运行这些方法,它们会返回不同的结果。

这是(基本)代码:

def compute_followers
  followers = Follower.where({ user_id: user_id, is_following: true }).count # => returns 10 always

  calculate_differences
  thread1 = Thread.new { process_new_followers }
  thread2 = Thread.new { process_lost_followers }
  thread1.join
  thread2.join

end

def process_new_followers
  puts Follower.where({ user_id: user_id, is_following: true }).count # => returns 0 if threaded and 10 if not
  ... I commented out this code so it only prints the count and nothing changes, so no db changes are happening in this method
end

def process_lost_followers
  puts Follower.where({ user_id: user_id, is_following: true }).count # => returns 0 if threaded and 10 if not
  ... I commented out this code so it only prints the count and nothing changes, so no db changes are happening in this method
end

为什么线程会影响这个SQL查询?

1 个答案:

答案 0 :(得分:2)

由于这是在使用ActiveRecord的Rails应用程序中,Rails将回滚其测试套件中的所有事务。由于你在一个线程中走出它,事务很可能已经回滚,这可以解释为什么你看到线程中的0计数和非线程调用中的10计数。