1
有人可以给出一个具体的例子来演示非线程安全吗? (以类似的方式,以一个运作版本矿下面如果可能的)Ruby请给出一个简单的非线程安全示例
我需要演示非线程安全操作,使得我可以断言上的失败,并且然后执行互斥锁,使得一个示例类我可以测试我的代码是线程安全的。
我已经尝试了以下但没有成功,因为线程似乎并行运行。假设红宝石+ =操作者不是线程,该测试总是通过时,它不应:
class TestLock
attr_reader :sequence
def initialize
@sequence = 0
end
def increment
@sequence += 1
end
end
#RSpec test
it 'does not allow parallel calls to increment' do
test_lock = TestLock.new
threads = []
list1 = []
list2 = []
start_time = Time.now + 2
threads << Thread.new do
loop do
if Time.now > start_time
5000.times { list1 << test_lock.increment }
break
end
end
end
threads << Thread.new do
loop do
if Time.now > start_time
5000.times { list2 << test_lock.increment }
break
end
end
end
threads.each(&:join) # wait for all threads to finish
expect(list1 & list2).to eq([])
end
线程是非确定性的。这就是他们如此丑陋的原因。你不能让他们确定性地失败。即使您的锁定不正确,他们有时也会工作,无论如何。你用你的代码完美地演示了它,它适用于YARV,在JRuby和Rubinius上失败。 –