Threads that share
In lesson 124 three threads “downloaded” at once, started with Thread.new and collected with value. Each worked on its own; nothing was shared. As soon as threads write to the same thing – a total of hours, a list of exported files – a new kind of bug appears, one that comes and goes with timing. This lesson shows it and the two tools Ruby has against it: Mutex and Queue.
The GVL in one paragraph
CRuby has a Global VM Lock (GVL): only one thread at a time runs Ruby code. A thread that waits – for the network, a file, the database, sleep – lets go of the lock, and another thread runs meanwhile. So threads make waiting faster (ten exports that each wait a second take one second, not ten), but not computing: four threads adding up numbers take as long as one – they only take turns. For computing on several cores there are Ractors and processes. And the GVL does not protect your data: Ruby may switch threads between any two steps of your code.
A race you can see
Three workers each book five hours onto a shared total. Each booking reads the total, waits a moment (as a database would) and writes the total plus one back:
total = 0
workers = 3.times.map do
Thread.new do
5.times do
before = total
sleep 0.01 # the moment another thread steps in
total = before + 1
end
end
end
workers.each(&:join)
total5, not 15. All three threads read the same total, sleep, and each writes back its old value plus one – two of every three bookings are lost. This is a race condition: the result depends on who gets there first. total += 1 has the same gap – it is a read, an addition and a write; without the sleep a thread switch only rarely lands in the gap, and that is worse: the bug shows up once a month, in production.
A Mutex (mutual exclusion) is a lock: synchronize lets only one thread at a time into its block; the others wait at the door until it is out again:
total = 0
lock = Mutex.new
workers = 3.times.map do
Thread.new do
5.times do
lock.synchronize do # one thread at a time
before = total
sleep 0.01
total = before + 1
end
end
end
end
workers.each(&:join)
total15 – and slower, since the threads now wait for each other. So lock only what must happen in one piece (reading and writing the total), not the slow work around it. And a thread may not lock a lock it already holds: synchronize inside synchronize on the same Mutex raises a ThreadError (deadlock; recursive locking).
Queue: handing out work
Often threads need not share a total at all if they hand work over instead. Queue is a thread-safe line: push (or <<) adds at the back, pop takes from the front – and waits while the queue is empty. Once the producer calls close, pop returns nil on an empty queue, so while (job = queue.pop) ends by itself. Here a producer hands projects to two exporters:
jobs = Queue.new
producer = Thread.new do
%w[website shop app newsletter intranet].each do |project|
jobs << project
sleep 0.05 # a new project comes in
end
jobs.close # no more jobs: pop returns nil once the queue is empty
end
exporters = 2.times.map do |n|
Thread.new do
files = []
while (project = jobs.pop)
puts "exporter #{n}: #{project}"
sleep 0.1 # exporting takes a while
files << "#{project}.csv"
end
files
end
end
producer.join
exporters.map(&:value)Every project was exported exactly once, by whichever exporter was free – no Mutex needed, the Queue does the locking. value waits for its thread like join and then returns the last value of its block: here each exporter's list of files. (Which exporter gets which project depends on timing; on your machine the split may differ.)
When a thread fails
An exception ends only its own thread; the main thread goes on. By default (report_on_exception is true) Ruby prints a report to stderr the moment the thread dies – otherwise the error might go unnoticed. The exception itself waits: join or value raise it again in the thread that asks, where you can rescue it:
export = Thread.new do
Thread.current.report_on_exception = false # no report on stderr
sleep 0.1
raise ArgumentError, "project shop has no hours"
end
puts "main thread carries on, export alive: #{export.alive?}"
begin
export.value
rescue ArgumentError => e
"caught in the main thread: #{e.message}"
endHere the thread switches the report off itself, since we collect the error with value anyway. Otherwise leave it on: a thread nobody joins would die silently.
TimeLedger below books hours the way the first demo did – four threads lose most of them, and the total comes out at 10 instead of 40. Give the ledger a Mutex (one per ledger, made in initialize) and make book safe with synchronize. Keep the sleep: it is the slow database, and the total must still be right.class TimeLedger
attr_reader :total
def initialize
@total = 0
end
def book(hours)
before = @total
sleep 0.01 # writing to the database takes a moment
@total = before + hours
end
end
ledger = TimeLedger.new
4.times.map { Thread.new { 5.times { ledger.book(2) } } }.each(&:join)
ledger.total # 4 threads x 5 bookings x 2 hours: should be 40