Ruby: threading basics
This course covers how Ruby threads behave once they are running. It shows how to read a thread's lifecycle with Thread#status and alive?, and how report_on_exception and abort_on_exception treat a thread that raises. It builds a deadlock from two mutexes locked in opposite order and shows it safely with join timeouts. It uses Queue and SizedQueue to pass work between threads with backpressure. Finally, it times the GVL with Benchmark.realtime: threads give a large speedup for I/O-bound work and almost none for CPU-bound work.
What you'll learn
- ✓Reading a thread's lifecycle with Thread#status and alive?
- ✓Handling thread exceptions with report_on_exception and abort_on_exception
- ✓Reproducing a deadlock and avoiding it with consistent lock ordering
- ✓Passing work between threads with Queue and SizedQueue
- ✓Measuring the GVL with Benchmark.realtime for I/O-bound and CPU-bound work
Thread#status and the thread lifecycle
The lesson "Threads and concurrency", in the intern course Operating system basics, covered process against thread and concurrency against parallelism. It also covered the GVL and why it's released during I/O, Thread.new/.join, a race-condition demo fixed with Mutex#synchronize, and Puma's model of…
Read the full lesson free →Curriculum
7 lessonsThread#status and the thread lifecycle
Reading Thread#status and alive? to tell a running thread from one that finished, and a normal finish from a crash.
abort_on_exception and report_on_exception
How report_on_exception logs a thread's unhandled exception and abort_on_exception raises it again in the main thread.
A real deadlock: two mutexes, opposite order
Two mutexes locked in opposite order produce a deadlock, shown with join timeouts and fixed by consistent lock ordering.
Queue and SizedQueue: thread-safe handoffs
Using Queue and SizedQueue to hand work between producer and consumer threads, with blocking pops and backpressure.
Measuring the GVL release with benchmark
Timing sequential against concurrent sleep calls with Benchmark.realtime shows the GVL released during I/O, with a 7.88x speedup.
CPU-bound work proves the GVL limit
The same benchmark with pure arithmetic shows almost no speedup, because CPU-bound threads take turns holding the GVL.
Putting it together
A review of thread status, exception settings, deadlocks, queues and the two GVL measurements from the course.