0
0
Rubyprogramming~20 mins

Thread creation and execution in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Thread Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of simple thread execution
What is the output of this Ruby code that creates and runs a thread?
Ruby
thread = Thread.new { puts "Hello from thread" }
thread.join
puts "Main thread finished"
A
Hello from thread
Main thread finished
B
Main thread finished
Hello from thread
CHello from thread
DMain thread finished
Attempts:
2 left
💡 Hint
The main thread waits for the new thread to finish before printing the last line.
Predict Output
intermediate
2:00remaining
Thread variable scope
What will be the output of this Ruby code involving threads and variables?
Ruby
message = "Hello"
thread = Thread.new { message = "Hi from thread" }
thread.join
puts message
AHello
BHi from thread
Cnil
DThreadError
Attempts:
2 left
💡 Hint
Threads share variables unless they are local to the thread block.
Predict Output
advanced
2:00remaining
Race condition demonstration
What is the output of this Ruby code with two threads incrementing a shared counter?
Ruby
counter = 0
threads = []
2.times do
  threads << Thread.new do
    1000.times { counter += 1 }
  end
end
threads.each(&:join)
puts counter
AThreadError
B1000
C2000
DA number less than 2000
Attempts:
2 left
💡 Hint
Incrementing a shared variable without synchronization can cause lost updates.
Predict Output
advanced
2:00remaining
Thread exception handling
What happens when a thread raises an exception that is not rescued inside it?
Ruby
thread = Thread.new do
  raise "Oops"
end
thread.join
puts "Main thread continues"
AUncaught exception terminates the program
BMain thread continues
CThread silently dies, main thread continues
DDeadlock occurs
Attempts:
2 left
💡 Hint
By default, unhandled exceptions in threads cause the whole program to terminate.
🧠 Conceptual
expert
2:00remaining
Thread synchronization with Mutex
Why is using a Mutex important when multiple threads modify a shared variable?
AIt prevents race conditions by allowing only one thread to access the variable at a time
BIt allows threads to share local variables safely
CIt automatically fixes syntax errors in thread code
DIt speeds up the program by running threads in parallel without waiting
Attempts:
2 left
💡 Hint
Think about how to avoid two threads changing the same data at the same time.