13.2. Synchronizing Threads

Why is synchronization necessary? It is because the “interleaving” of operations causes variables and other entities to be accessed in ways that are not obvious from reading the code of the individual threads. Two or more threads accessing the same variable may interact with each other in ways that are unforeseen and difficult to debug.

Let’s take this simple piece of code as an example:

x = 0
t1 = Thread.new do
  1.upto(1000) do
    x = x + 1
  end
end

t2 = Thread.new do
  1.upto(1000) do
    x = x + 1
  end
end

t1.join
t2.join
puts x

The variable x starts at zero. Each thread increments it a thousand times. Logic tells us that x must be 2000 when it is printed out.

But you may find that the actual results contradict this logic. ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.