Bird
Raised Fist0
Rubyprogramming~10 mins

Thread creation and execution in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Thread creation and execution
Start main program
↓
Create new thread
↓
Thread starts running block
↓
Thread executes code
↓
Thread finishes
↓
Main program continues or waits
↓
Program ends
The main program creates a thread that runs code concurrently. The thread executes its block and finishes, while the main program can continue or wait.
Execution Sample
Ruby
thread = Thread.new do
  puts "Hello from thread"
end
thread.join
puts "Main program ends"
This code creates a thread that prints a message, waits for it to finish, then prints a final message.
Execution Table
StepActionThread StateOutputMain Program State
1Main program startsNo thread yetRunning
2Create new thread with blockNew thread createdRunning
3Thread starts running blockRunningHello from threadRunning
4Thread finishes blockFinishedHello from threadWaiting at join
5Main program resumes after joinFinishedHello from threadRunning
6Main program prints final messageFinishedHello from thread Main program endsRunning
7Program endsFinishedHello from thread Main program endsExited
💡 Thread finishes execution and main program ends after printing all messages.
Variable Tracker
VariableStartAfter Step 2After Step 4Final
threadnilThread object createdThread finishedThread finished
Key Moments - 2 Insights
Why does the main program wait at thread.join?
Because thread.join pauses the main program until the thread finishes, as shown in execution_table step 4.
What happens if we don't call thread.join?
The main program may finish before the thread runs or completes, so the thread's output might not appear, unlike step 4 where join waits.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the thread state at step 3?
ANew thread created
BFinished
CRunning
DNo thread yet
💡 Hint
Check the 'Thread State' column at step 3 in the execution_table.
At which step does the main program wait for the thread to finish?
AStep 4
BStep 3
CStep 2
DStep 6
💡 Hint
Look at the 'Main Program State' column to find when it is 'Waiting at join'.
If we remove thread.join, what will likely happen to the output?
ABoth messages print in order
BOnly 'Main program ends' prints
COnly 'Hello from thread' prints
DNo output prints
💡 Hint
Without join, main program may finish before thread runs, so only main message prints.
Concept Snapshot
Thread creation in Ruby:
thread = Thread.new { code }
Thread runs code concurrently.
Use thread.join to wait for thread to finish.
Without join, main may finish first.
Threads allow parallel tasks.
Full Transcript
This example shows how Ruby creates and runs a thread. The main program starts and creates a new thread with Thread.new. The thread runs the code block, printing 'Hello from thread'. The main program calls thread.join to wait until the thread finishes. After the thread ends, the main program prints 'Main program ends' and then exits. Variables like 'thread' hold the thread object, which changes state from created to finished. Key points include understanding that join pauses the main program until the thread completes, and without join, the main program might finish before the thread runs. The execution table tracks each step, thread state, output, and main program state to visualize the flow.

Practice

(1/5)
1. What does Thread.new do in Ruby?
easy
A. It creates a new thread to run code concurrently.
B. It pauses the current thread until another finishes.
C. It terminates all running threads immediately.
D. It converts a method into a thread-safe version.

Solution

  1. Step 1: Understand the purpose of Thread.new

    Thread.new starts a new thread that runs the code inside its block concurrently with the main program.
  2. Step 2: Compare options with the behavior

    Only It creates a new thread to run code concurrently. correctly describes creating a new thread to run code at the same time as other threads.
  3. Final Answer:

    It creates a new thread to run code concurrently. -> Option A
  4. Quick Check:

    Thread.new = create thread [OK]
Hint: Remember: Thread.new starts a new thread block [OK]
Common Mistakes:
  • Confusing thread creation with thread termination
  • Thinking Thread.new pauses threads
  • Assuming Thread.new modifies methods
2. Which of the following is the correct syntax to create and start a thread in Ruby?
easy
A. Thread.start puts 'Hello from thread'
B. Thread.run { puts 'Hello from thread' }
C. Thread.create do puts 'Hello from thread' end
D. Thread.new { puts 'Hello from thread' }

Solution

  1. Step 1: Recall correct thread creation syntax

    The correct way is Thread.new { ... } where the block contains the code to run.
  2. Step 2: Check each option

    Thread.new { puts 'Hello from thread' } uses Thread.new with a block correctly. Options A, C, and D use invalid or non-existent methods or syntax.
  3. Final Answer:

    Thread.new { puts 'Hello from thread' } -> Option D
  4. Quick Check:

    Use Thread.new { } for threads [OK]
Hint: Use Thread.new with a block to start threads [OK]
Common Mistakes:
  • Using Thread.start without a block
  • Mistyping method names like Thread.create
  • Using Thread.run which does not exist
3. What will be the output of this Ruby code?
thread = Thread.new { 5.times { |i| puts i; sleep 0.1 } }
thread.join
puts 'Done'
medium
A. 0 1 2 3 4 Done (each number on its own line)
B. Done 0 1 2 3 4 (each number on its own line)
C. Only 'Done' is printed
D. No output because thread.join blocks forever

Solution

  1. Step 1: Understand thread execution and join

    The thread prints numbers 0 to 4 with a short pause. The main thread waits for it to finish because of thread.join.
  2. Step 2: Determine output order

    The numbers 0 to 4 print first, each on its own line, then after the thread finishes, 'Done' prints.
  3. Final Answer:

    0 1 2 3 4 Done (each number on its own line) -> Option A
  4. Quick Check:

    Thread prints numbers before main prints 'Done' [OK]
Hint: join waits for thread to finish before continuing [OK]
Common Mistakes:
  • Assuming 'Done' prints before numbers
  • Thinking join blocks forever
  • Ignoring sleep delays in thread
4. Identify the error in this Ruby code snippet:
thread = Thread.new do
  puts 'Start'
  sleep 1
  puts 'End'
end
puts 'Waiting'
thread.join
medium
A. The thread block is missing a closing end.
B. The main thread does not wait for the new thread to finish.
C. There is no error; the code runs correctly.
D. The sleep method cannot be used inside a thread.

Solution

  1. Step 1: Check thread block syntax

    The thread block is properly closed with end. Syntax is correct.
  2. Step 2: Verify thread execution and join

    The main thread prints 'Waiting' then calls thread.join to wait for the thread to finish. This is correct usage.
  3. Final Answer:

    There is no error; the code runs correctly. -> Option C
  4. Quick Check:

    Thread syntax and join usage are correct [OK]
Hint: Check block ends and join usage carefully [OK]
Common Mistakes:
  • Thinking sleep is invalid in threads
  • Assuming join is missing
  • Miscounting block ends
5. You want to create 3 threads that each print their thread number (1, 2, 3) and then print 'Finished' after all threads complete. Which code correctly achieves this?
hard
A. 3.times do |i| Thread.new { puts i + 1 } end puts 'Finished'
B. threads = [] 3.times do |i| threads << Thread.new { puts i + 1 } end threads.each(&:join) puts 'Finished'
C. threads = [] 3.times do |i| threads << Thread.new { puts i } end puts 'Finished' threads.each(&:join)
D. threads = [] 3.times do |i| threads << Thread.new { puts i + 1 } end puts 'Finished' threads.each(&:join)

Solution

  1. Step 1: Create threads storing them in an array

    threads = [] 3.times do |i| threads << Thread.new { puts i + 1 } end threads.each(&:join) puts 'Finished' correctly creates 3 threads, each printing i + 1 (1, 2, 3), and stores them in threads.
  2. Step 2: Wait for all threads to finish before printing 'Finished'

    threads = [] 3.times do |i| threads << Thread.new { puts i + 1 } end threads.each(&:join) puts 'Finished' calls threads.each(&:join) to wait for all threads, then prints 'Finished'. This ensures 'Finished' prints last.
  3. Final Answer:

    threads = [] 3.times do |i| threads << Thread.new { puts i + 1 } end threads.each(&:join) puts 'Finished' -> Option B
  4. Quick Check:

    Store threads, join all, then print [OK]
Hint: Join all threads before printing final message [OK]
Common Mistakes:
  • Not storing threads to join later
  • Printing 'Finished' before threads complete
  • Using wrong thread index values
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard