Threads and fibers
Threads
A thread runs a block alongside your main program. The main program keeps going immediately — nothing waits unless you ask it to. Call join when you need the result before continuing:
worker = Thread.new do puts "hello from a thread" end worker.join puts "done"
ruby threads.rb
hello from a thread
done
Without join the program could exit before the thread prints anything. Read the computed value with value instead — it joins implicitly and returns whatever the block evaluated to.
The GVL
CRuby runs threads on top of the Global VM Lock (GVL, historically called
the GIL): only one thread executes Ruby code at a time. Threads still help
whenever a thread waits — network responses, files, sleep — because a
waiting thread releases the lock for the others.
Pure computation does not get faster with more threads on CRuby: two
threads crunching numbers take turns instead of running in parallel. For
CPU-bound work use processes (see
lesson 12.13,
later) or
JRuby/TruffleRuby, which have no GVL.
Fibers
A fiber is cooperative: it runs only when you resume it and pauses only where it yields. No surprises, no races — you control every switch:
fiber = Fiber.new do Fiber.yield 1 Fiber.yield 2 end puts fiber.resume puts fiber.resume
ruby fibers.rb
1
2
Mutex
Threads share all variables, so code that reads a value and writes it back can interleave with another thread: a check followed by an action is no longer one step. A mutex lets only one thread inside the critical section at a time. Collect the squares of 0, 1, 2 under one:
results = [] mutex = Mutex.new workers = 3.times.map do |i| Thread.new do square = i * i mutex.synchronize { results << square } end end workers.each(&:join) puts results.sort.inspect
ruby mutex.rb
[0, 1, 4]
Rule of thumb: share as little as possible, guard what you share with a mutex, and join every thread you start.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
joinon a thread do?Answer
Waits for the thread to finish
join blocks the caller until the thread is done, which is how a program keeps its last lines in order.
-
On CRuby, what does the Global VM Lock mean for two threads that only compute numbers?
Answer
Only one thread runs Ruby code at a time, so the work is not faster
The lock lets one thread run Ruby code at a time; threads help when one of them waits, not when both compute.
-
A fiber is cooperative. What does that mean?
Answer
It switches only when it is resumed or when it yields
Nothing runs inside a fiber until resume, and the fiber stops at its own Fiber.yield calls.
-
What does
mutex.synchronize { ... }guarantee?Answer
Only one thread runs the block at a time
The mutex is a lock: a second thread waits at synchronize until the first one leaves the block.
-
What does this program print?
worker = Thread.new { puts "in" } worker.join puts "out"Answer
in / out
join waits, so the thread prints first and the main program prints after it.
-
What does this program print?
fiber = Fiber.new do Fiber.yield "a" "b" end p fiber.resume p fiber.resumeAnswer
"a" / "b"
The first resume runs to the yield and returns "a"; the second runs to the end and returns "b".
-
What does this program print?
results = [] mutex = Mutex.new threads = 3.times.map do |i| Thread.new { mutex.synchronize { results << i } } end threads.each(&:join) p results.sortAnswer
[0, 1, 2]
The threads run in any order, the sort puts the values in order, and the mutex keeps each append whole.
-
What does this program print?
t = Thread.new { 2 + 3 } p t.valueAnswer
5
value joins the thread and returns what its block evaluated to, which is 5.
-
A program starts a thread that prints a line and never calls
join. What can happen?Answer
The program may exit before the line is printed
The main program does not wait, so the process can end while the thread is still about to print.
-
Why does shared state need a mutex even on CRuby?
Answer
Code that reads a value and writes it back can interleave with another thread
The GVL is not a lock around your own sequence of steps: another thread can run between the read and the write.
Article author: Arthur Isaev