9. Race Condition
Example 3
class Item
class << self; attr_accessor :price end
@price = 0
end
(1..10).each { Item.price += 10 }
puts "Item.price = #{Item.price}“
Output :
varun@kiprosh-varun:~/projects/test$ ruby test.rb
Item.price = 100
10. Race Condition
Example 4
class Item
class << self; attr_accessor :price end
@price = 0
end
threads = (1..10).map do |i|
Thread.new(i) do |i|
item_price = Item.price # Reading value
sleep(rand(0..2))
item_price += 10
# Updating value
sleep(rand(0..2))
Item.price = item_price # Writing value
end
end
threads.each {|t| t.join}
puts "Item.price = #{Item.price}“
12. Race Condition
The race condition is fundamentally due to the multi-step process of
changing a variable.
register = i
# read the current value from RAM into a register
register = register + 1 # increment it by one
i = register
# write the value back to the variable in RAM
●
OS can stop Thread 1 and start executing Thread 2 at any point in time.
13. Race Condition
i=0
# OS is running Thread 1
register = i # 0
register = register + 1 # 1
# OS switches to Thread 2
register = i # 0
register = register + 1 # 1
i = register # 1
# Now OS switches back to Thread 1
i = register # 1
15. Mutual Exclusion
class Item
class << self; attr_accessor :price end
@price = 0
end
mutex = Mutex.new
threads = (1..10).map do |i|
Thread.new(i) do |i|
mutex.synchronize do
item_price = Item.price # Reading value
sleep(rand(0..2))
item_price += 10
# Updating value
sleep(rand(0..2))
Item.price = item_price # Writing value
end
end
end
threads.each {|t| t.join}
puts "Item.price = #{Item.price}"