Search⌘ K
AI Features

...continued

Learn why synchronizing both reads and writes to shared data is crucial in Ruby concurrency. Understand atomic operations, torn values, and proper mutex usage to ensure thread safety. This lesson helps you grasp key concepts in Ruby's threading model and synchronization mechanisms essential for reliable concurrent programming.

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:

Ruby
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 ...