Concurrency & Delay in Ruby
Explore Ruby threads, the Global Interpreter Lock (GIL), sleep, and basic concurrent programming techniques.
Waiting & Delay
Ruby's sleep method pauses the current thread. Unlike Node.js's async model, sleep blocks the thread completely. For non-blocking delays, use threads.
1. sleep — Pause Execution
Block current thread for N seconds.
2. Non-Blocking Delay with Thread
Run delay in background thread.
Threads
Ruby threads are OS-level threads but subject to the Global VM Lock (GVL, also called GIL) in MRI Ruby. The GVL prevents true parallel execution of Ruby code, but threads still help with I/O-bound tasks.
1. Creating Threads
Run code concurrently.
2. Thread Return Value
Get result from a thread.
3. Parallel I/O Tasks
Speed up I/O-bound work with threads.
The Global VM Lock (GVL)
MRI Ruby (the standard Ruby interpreter) uses a Global VM Lock that prevents multiple threads from executing Ruby code at the same time. This limits CPU-bound parallelism. I/O-bound tasks still benefit from threads since the GVL is released during I/O.
1. GVL Impact on CPU Work
Threads do not speed up CPU-bound tasks in MRI.
2. Ractor — True Parallelism (Ruby 3+)
Ractors bypass the GVL for parallel CPU work.
Thread Safety & Mutex
When multiple threads write to shared data, you can get race conditions. A Mutex (mutual exclusion lock) ensures only one thread accesses a critical section at a time.
1. Race Condition Without Mutex
See the problem first.
2. Mutex — Safe Shared Counter
Protect critical section.
Coordinating Multiple Threads
You can run multiple threads and collect all their results at the end — similar to Promise.all() in Node.js or asyncio.gather() in Python.
1. Wait for All Threads (map + join)
Run tasks in parallel, collect results.
2. Thread with Timeout
Cancel a thread after a time limit.