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程序来测试互斥锁.synchronize并在每次运行时得到0,但每次我运行这个程序时它都会给我随机值.需要帮助解决这个问题,以获得0,并帮助我了解如何在Ruby中使用互斥锁和锁