Parallel work without a framework
A worker pool
A pool is a queue of jobs and a fixed number of threads that take them. The queue does the locking; the pool decides how many run at once:
count = Integer(ARGV.fetch(0, "4")) jobs = Queue.new results = Queue.new 1.upto(8) { |i| jobs << i } workers = count.times.map do Thread.new do loop do job = begin jobs.pop(true) rescue ThreadError break end results << job * job end end end workers.each(&:join) values = [] values << results.pop until results.empty? p values.sort
ruby workers.rb 4
[1, 4, 9, 16, 25, 36, 49, 64]
pop(true) is the non-blocking form: it raises ThreadError when the queue is empty, and the worker exits. That is the shortest pool that finishes, and it works because all the jobs are queued before the workers start.
Ending the pool
A pool that reads jobs while they arrive cannot use the empty check: a worker would exit before the next job is pushed. The reliable end is a sentinel per worker:
count = 4 jobs = Queue.new results = Queue.new 1.upto(8) { |i| jobs << i } count.times { jobs << :stop } workers = count.times.map do Thread.new do while (job = jobs.pop) != :stop results << job * job end end end workers.each(&:join) values = [] values << results.pop until results.empty? p values.sort
ruby pool.rb
[1, 4, 9, 16, 25, 36, 49, 64]
One :stop per worker, pushed after the last job, means every worker gets one and none blocks forever. A single sentinel leaves the other workers waiting on an empty queue, which is the hang that a timeout in the test would catch.
Fork for CPU work
Squares are cheap; real CPU work in Ruby needs processes because of the GVL. The same pool shape with fork uses every core:
ruby -e 'pids = 4.times.map { |i| fork { sleep 0.1; exit!(i) } }; p pids.map { |pid| Process.wait2(pid).last.exitstatus }'
[0, 1, 2, 3]
A real job pool splits the input into ranges, forks one process per range and collects the results through a pipe or a temporary file. The parent waits on all of them and fails the run when any exitstatus is not zero.
Ractor in one example
A Ractor is Ruby's actor: a unit of parallelism with its own objects, communicating by messages. One example is enough to see the shape:
ruby -e 'r = Ractor.new { 1 + 1 }; p r.take'
-e:1: warning: Ractor is experimental, and the behavior may change in future versions of Ruby! Also there are many implementation issues.
2
The warning is part of the output on Ruby 3.4 and should be read as it says: the API works, the implementation is not finished, and a gem that depends on it is early. Ractor.new { } takes arguments and returns values by message, and only shareable objects can cross the boundary.
What to watch for
More workers than cores makes a CPU pool slower, not faster: the context
switches cost more than the work. Start with the number of cores, measure,
and stop there.
A pool needs a bounded queue and a failure path. A producer that outruns
the consumers grows the queue until the memory goes; a worker that raises
must report the error to the parent, or the job silently disappears.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does this program print?
jobs = Queue.new jobs << :a jobs << :b p jobs.pop(true) p jobs.pop(true)Answer
:a / :b
A Queue is first in, first out, and the non-blocking pop returns the first item while one is there.
-
Why does a pool that takes jobs as they arrive need one sentinel per worker?
Answer
A worker blocks on pop, so each one needs its own value to end the loop
A single sentinel ends one worker and leaves the others blocked on an empty queue, so the last join never returns.
-
What does this program print?
jobs = Queue.new results = Queue.new 3.times { |i| jobs << i } 2.times { jobs << :stop } workers = 2.times.map do Thread.new do while (job = jobs.pop) != :stop results << job * 2 end end end workers.each(&:join) p results.sizeAnswer
3
Three jobs are queued and two workers take them; the two sentinels end both loops and every result is one job doubled.
-
Why is
forkused for CPU-bound work in a pool?Answer
Because the GVL lets only one thread run Ruby code at a time
Processes are the only way to use several cores for arithmetic on CRuby, at the cost of copying memory and passing results back.
-
What does this program print on standard output?
r = Ractor.new { 21 * 2 } p r.takeAnswer
42
take receives the message the block returned; the experimental warning goes to stderr and does not stop the program.
-
Where does the experimental Ractor warning of Ruby 3.4 appear?
Answer
On standard error, before the result on standard output
The interpreter writes it to stderr, which a terminal shows before the buffered stdout, so the page shows both lines.
-
What does this program print?
results = Queue.new workers = 3.times.map { |i| Thread.new { results << i * i } } workers.each(&:join) values = [] values << results.pop until results.empty? p values.sortAnswer
[0, 1, 4]
Each worker pushes the square of its index, and the sort makes the print independent of the order the threads finished in.
-
What happens when a pool has more workers than cores?
Answer
A CPU pool gets slower, because the context switches cost more than the work they share
The page starts at the number of cores and measures; extra workers add switching overhead to a CPU-bound job.
-
Which failure does a pool without a bounded queue have?
Answer
A producer that runs faster than the workers grows the queue until the memory goes
Queue is safe for two threads but not bounded, so back-pressure must come from somewhere else when the producer outruns the consumers.
-
What does a worker have to do when its job raises?
Answer
It should rescue and report the error to the parent, or the job silently disappears
A thread that dies keeps the failure to itself until a join, so a pool needs an error channel or a join that re-raises.
Article author: Arthur Isaev