Ruby - Main Thread and Sub-threads

1. Introduction

Threading in Ruby allows for the concurrent execution of tasks. While many are familiar with the creation of sub-threads, it's essential to recognize that a program also has a main thread, which is where the execution starts. In this post, we will demonstrate the main thread and how it interacts with sub-threads in Ruby.

The main thread is the initial thread of execution when a program starts. Every Ruby program has at least the main thread, and it can spawn additional sub-threads to perform tasks concurrently. These sub-threads run in parallel with the main thread and with each other, allowing for efficient multitasking.

2. Program Steps

1. Start the main program.

2. Print a message from the main thread.

3. Create and start multiple sub-threads.

4. Optionally, wait for the sub-threads to finish using the join method.

5. Print a concluding message from the main thread.

3. Code Program

# Starting the main program (main thread starts by default)
# Step 2: Print a message from the main thread
puts "Main thread starts."
# Step 3: Create and start sub-threads
sub_thread1 = do
  3.times do |i|
    puts "Sub-thread 1 printing: #{i}"
sub_thread2 = do
  3.times do |i|
    puts "Sub-thread 2 printing: #{i}"
# Step 4: Wait for sub-threads to finish
# Step 5: Print concluding message from the main thread
puts "Main thread concludes."


Main thread starts.
Sub-thread 1 printing: 0
Sub-thread 2 printing: 0
Sub-thread 1 printing: 1
Sub-thread 2 printing: 1
Sub-thread 1 printing: 2
Sub-thread 2 printing: 2
Main thread concludes.


1. Main thread: This is the primary thread of execution in any Ruby program. In our example, the main thread starts by default when the program runs and prints the initial and concluding messages.

2. Sub-thread: These are threads spawned from the main thread to carry out tasks concurrently. We've created two sub-threads in our example, sub_thread1 and sub_thread2.

3. This method creates a new thread and starts its execution. The code inside the block is what the thread will execute.

4. sleep: This method pauses the thread for a specified number of seconds. It's used here to simulate time-consuming tasks and to make the output easier to read.

5. join: This method is called on a thread object (like sub_thread1) and causes the main thread to wait for the sub-thread to finish its execution.

By understanding and properly managing the main thread and sub-threads, developers can harness the power of concurrent execution in Ruby.