...continued

This lesson continues the discussion of Mutex in Ruby.

We'll cover the following...

A mistaken belief is that we only need to synchronize access to shared resources when writing to them and not when reading them. Consider the snippet below. We have an array of size two initialized with true values. The writer thread flips the boolean values in all the array elements in a loop. Since the array is shared, we guard the write to the array in a mutex synchronize block. We have another reader thread that outputs the array to the console. With proper synchronization, the output on the console will consist of either all true or all false values. Run the widget below and see what happens:

Press + to interact
mutex = Mutex.new
array = []
2.times do |i|
array[i] = true
end
writer = Thread.new do
while true
mutex.synchronize {
array.each_with_index do |el, i|
array[i] = !array[i]
end
}
# sleep(0.01)
end
end
reader = Thread.new do
while true
puts array.to_s()
sleep(0.1)
end
end
sleep(5)

You can ...