ruby-on-rails - 为什么 .with_lock 没有按我的预期工作?

标签 ruby-on-rails multithreading activerecord locking

我希望下面的代码能够强制对其中的代码块进行独占访问,但事实并非如此。在我的测试中,每个线程都能够同时运行该 block 。

假设Rails环境和用户是一个activerecord对象。另请注意,这是我编写的一个有点随意的测试,目的是解决我在 Web 请求中遇到的并发问题。

user = User.first
threads = []

3.times do |i|
    threads << Thread.new do
        user.with_lock do
            puts "start: #{i}"
            sleep 1
            puts "stop: #{1}"
        end
    end
end

threads.each(&:join)

预期输出:

start: 1
stop: 1
start: 2
stop: 2
start: 3
stop: 3

实际输出:

start: 1
start: 2
start: 3
stop: 1
stop: 2
stop: 3

我错过了什么? Rails .with_lock 不能在标准 ruby​​ 线程中工作吗?或者,这可能是由于我的测试环境使用sqlite3造成的?


最佳答案

它似乎与 sqlite3 有关。

关于ruby-on-rails - 为什么 .with_lock 没有按我的预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43924883/

相关文章:

python - 多处理还是多线程?

c++ - 改进多线程的一般技巧(在 C++ 中)

ruby-on-rails - 编码或序列化 ActiveRecord 对象

ruby-on-rails - 在 Ruby 中打开并读取 Google Drive 中的文件

ruby-on-rails - 从 Rails 中的模型中获取所有验证方法

javascript - 使用 Rails View 定期轮询数据库更新而不刷新

ruby-on-rails - 在 Rails 3 中设置 session 超时

css - Rails Awesome 字体

python - python中的延迟函数

mysql - 在 activerecord 级别捕获 MySql 触发器