使用互斥体的 Ruby 线程并发问题

问题描述 投票:0回答:1
require 'thread'

mutex = Mutex.new


shared_resource = 0

  for i in 0..10000
    Thread.new do
      mutex.synchronize { shared_resource += 1 }
    end
    Thread.new do
      mutex.synchronize { shared_resource -= 1 }
    end
  end

puts shared_resource

我正在尝试运行这个 Ruby 程序来测试 mutex.synchronize 并在每次运行时得到 0 但每次我运行这个程序时它都会给我随机值。需要帮助解决这个问题以获得 0 并帮助我了解如何在 Ruby 中使用互斥锁和锁定

ruby-on-rails ruby mutex
1个回答
0
投票

您的问题不是互斥锁,因为同步会在块执行期间锁定它。您的问题是,当您到达

puts shared_resource
时,线程执行尚未完成。

要解决此问题,您需要通过调用

Thread#join
确保所有线程已完成,例如:

require 'thread'

mutex = Mutex.new

shared_resource = 0
threads = []

400.times do |i|
  threads << Thread.new do
    mutex.synchronize {shared_resource += 1}
  end
  threads << Thread.new do
    mutex.synchronize {shared_resource -= 1}
  end
end

threads.map(&:join)

puts shared_resource
#=> 0 
© www.soinside.com 2019 - 2024. All rights reserved.