0Pricing
Ruby Academy · Lesson

Threads

Concurrent execution.

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"

All lessons in this course

  1. Threads
  2. The GVL Explained
  3. Fibers
  4. Ractors
← Back to Ruby Academy