Threads, mutexes and queues
Mutex
Two threads that add to the same variable lose updates: the read, the add and the write are three steps, and the scheduler can switch between them. A Mutex makes the three steps one:
mutex = Mutex.new total = 0 10.times.map do Thread.new { mutex.synchronize { total += 1 } } end.each(&:join) p total
ruby mutex.rb
10
Ruby's GVL means only one thread runs Ruby code at a time, so the counter race is narrower than in C. It is not gone: a context switch can happen between the read and the write, and the result is a lost increment that appears once in a thousand runs.
Queue
Queue is the better default: a thread-safe hand-over with no shared variable to guard. push adds and pop takes, blocking when the queue is empty. A sentinel value ends the consumer:
queue = Queue.new producer = Thread.new { 3.times { |i| queue << i }; queue << :done } consumer = Thread.new do loop do item = queue.pop break if item == :done puts item end end producer.join consumer.join
ruby queue.rb
0
1
2
A producer and a consumer
The pair from the previous section with a counter instead of a print. The mutex is only around the shared total; the queue does its own locking:
queue = Queue.new total = 0 mutex = Mutex.new producer = Thread.new do 3.times { |i| queue << i } queue << :done end consumer = Thread.new do loop do item = queue.pop break if item == :done mutex.synchronize { total += item } end end producer.join consumer.join p total
ruby threads.rb
3
The consumer blocks on pop until there is work, so it does not spin. The sentinel ends the loop; a queue with no sentinel and no timeout is a program that hangs on the last join, which is the usual bug in a hand-written worker pool.
ConditionVariable
When a thread must wait for a condition and not for an item, ConditionVariable is the tool. It waits on a mutex and wakes when another thread signals:
mutex = Mutex.new ready = false cond = ConditionVariable.new waiter = Thread.new do mutex.synchronize do cond.wait(mutex) until ready puts "woke" end end sleep 0.1 mutex.synchronize do ready = true cond.signal end waiter.join
ruby condvar.rb
woke
The until ready is not decoration: a condition variable can wake spuriously, and the loop re-checks. A signal wakes one waiter, broadcast wakes all of them.
What to watch for
A mutex held across a network call serialises every thread behind the
slowest one. Hold it around the shared data and release it before the
I/O.
A thread that raises does not stop the program at that moment: the
exception is re-raised in the thread that joins it. The default
report_on_exception also prints it as soon as it
happens, so a failure disappears only when that is off and nothing joins
the thread.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does the global VM lock (GVL) of Ruby guarantee?
Answer
Only one thread runs Ruby code at a time, and the lock is released during blocking calls
The GVL serialises Ruby bytecode, which narrows a race but does not make a read, an add and a write one step.
-
Why does a counter shared by two threads need a mutex around
total += 1?Answer
The read, the add and the write are separate steps, and a thread switch between them loses an update
A switch between the read and the write lets both threads start from the same value, so one increment is overwritten.
-
What does this program print?
mutex = Mutex.new total = 0 10.times.map do Thread.new { mutex.synchronize { total += 1 } } end.each(&:join) p totalAnswer
10
Every increment runs inside the same mutex, and every thread is joined, so all ten updates land.
-
What does this program print?
q = Queue.new q << 1 q << 2 p q.size p q.pop p q.sizeAnswer
2 / 1 / 1
Two items are pushed, the pop removes the first one, and the size drops from two to one.
-
What does this program print?
q = Queue.new begin q.pop(true) rescue ThreadError => e puts e.class endAnswer
ThreadError
With the non-blocking flag a pop on an empty queue raises ThreadError instead of waiting for an item.
-
Why does a worker loop end on a sentinel value such as
:done?Answer
The consumer blocks on pop, so a queue with nothing to signal the end hangs the last join
pop waits for an item, so the consumer needs a value it recognises as the last one, or it never leaves the loop.
-
What does this program print?
thread = Thread.new { 40 + 2 } puts thread.valueAnswer
42
value waits for the thread and returns what its block returned.
-
What does this program print on standard output?
thread = Thread.new { raise ArgumentError, "bad" } begin thread.join rescue ArgumentError => e puts e.class endAnswer
ArgumentError
join re-raises the exception of the thread in the joining thread, where the rescue catches it; the default report_on_exception also prints the trace on stderr.
-
Why is
cond.wait(mutex) until readywritten with a loop and not onewait?Answer
A condition variable can wake without a signal, so the condition must be checked again
A spurious wake-up is allowed, so the thread re-reads the condition and waits again until it is really true.
-
What is the cost of holding a mutex across a network call?
Answer
Every other thread that needs the mutex waits behind the slowest call
The lock turns parallel work into a queue behind the network, so the shared data is guarded and the I/O happens outside the lock.
Article author: Arthur Isaev