Threads
Concurrent execution.
Threads is a free Ruby Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Ruby Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is a Thread?
A thread is an independent path of execution inside your program. Ruby lets you run several threads so that work can overlap in time.
- The main program runs in the main thread.
- You create more threads with
Thread.new. - Threads share the same memory, so they can read and write the same variables.
Threads are ideal when your program spends time waiting (network, disk, sleep), because one thread can wait while another keeps working.
Creating a Thread
Pass a block to Thread.new. The block runs in a new thread. Call join to wait for it to finish before the program exits.
t = Thread.new do
puts "Hello from the new thread"
end
t.join
puts "Main thread done"Why join Matters
When the main thread ends, Ruby exits and may not wait for other threads. join blocks the caller until the target thread completes.
Without join, the worker may never get a chance to print before the program quits.
t = Thread.new do
sleep 0.1
puts "Worker finished"
end
puts "Waiting..."
t.join
puts "All done"Many Threads at Once
You can launch a group of threads, collect them into an array, then join each one. This is a common pattern for parallel-ish I/O work.
threads = (1..3).map do |n|
Thread.new do
puts "Thread number " + n.to_s
end
end
threads.each(&:join)
puts "Finished all threads"Sharing Variables
Threads share memory. A variable defined before the thread is visible inside it. This is powerful but also dangerous if two threads write the same value.
counter = 0
t = Thread.new do
counter += 1
end
t.join
puts "Counter is " + counter.to_sRace Conditions
A race condition happens when threads interleave updates to shared data and the result depends on timing.
counter += 1is actually read, add, write.- Two threads can read the same old value and both write the same new value, losing an increment.
The fix is to coordinate access with a lock.
Mutex: A Lock
A Mutex (mutual exclusion) ensures only one thread runs the protected code at a time. Wrap the critical section in mutex.synchronize.
mutex = Mutex.new
counter = 0
threads = (1..5).map do
Thread.new do
mutex.synchronize do
counter += 1
end
end
end
threads.each(&:join)
puts "Counter is " + counter.to_sReturning a Value
Thread#value waits for the thread to finish and returns the value of its block, like an automatic join plus a result.
t = Thread.new do
2 + 3
end
puts "Result is " + t.value.to_sThread-Local Variables
Each thread can store its own values keyed by symbol with Thread.current[:key]. These are private to that thread and never shared.
t = Thread.new do
Thread.current[:name] = "worker"
puts "Inside: " + Thread.current[:name]
end
t.joinHandling Exceptions
If a thread raises an error, it stays silent until you call join or value, which re-raises it. Setting Thread.abort_on_exception = true makes errors crash the whole program immediately, which helps debugging.
t = Thread.new do
raise "boom"
end
begin
t.join
rescue => e
puts "Caught: " + e.message
endWhen Threads Help
Threads shine for I/O-bound work where time is spent waiting. They help less for CPU-bound work because of the GVL (covered next).
- Good: downloading many URLs, reading many files.
- Limited: heavy number crunching across cores.
Always protect shared mutable state with a Mutex.
Quick Check
Test your understanding of threads.
Recap: Threads
You learned the essentials of Ruby threads:
Thread.newstarts concurrent execution.joinwaits;valuewaits and returns a result.- Threads share memory, causing race conditions.
- A
Mutexwithsynchronizeprotects shared state. - Threads excel at I/O-bound work.
Next we explore why threads cannot fully use multiple CPU cores: the GVL.
Frequently asked questions
Is the “Threads” lesson free?
Yes — the full text of “Threads” is free to read here on the web, and the Ruby Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Ruby Academy course, upgrade to CoddyKit PRO.
What will I learn in “Threads”?
Concurrent execution. You practise Ruby Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Ruby Academy?
No prior experience is required. Ruby Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Threads” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Ruby Academy lesson?
Yes. Every Ruby Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.