According to this post, i += 1
is thread safe in MRI Ruby because the preemption only happens at the end of function call, not somewhere between i += 1
.
A repeatable test below shows that this is true:
But why while true do i += 1 end
is not thread safe, as shown by the second test below where thread1 is preempted by thread2 when thread1 is still executing while true do i += 1 end
?
Please help.
Below are the code reference:
test one:
100.times do
i = 0
1000.times.map do
Thread.new {1000.times {i += 1}}
end.each(&:join)
puts i
end
test two:
t1 = Thread.new do
puts "#{Time.new} t1 running"
i = 0
while true do i += 1 end
end
sleep 4
t2 = Thread.new do
puts "#{Time.new} t2 running"
end
t1.join
t2.join