Challenge - 5 Problems
Thread Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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"
Attempts:
2 left
💡 Hint
The main thread waits for the new thread to finish before printing the last line.
✗ Incorrect
The thread prints its message first. The main thread waits for it to finish because of join, then prints its message.
❓ Predict Output
intermediate2: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
Attempts:
2 left
💡 Hint
Threads share variables unless they are local to the thread block.
✗ Incorrect
The thread changes the shared variable message. After join, the main thread prints the updated value.
❓ Predict Output
advanced2: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
Attempts:
2 left
💡 Hint
Incrementing a shared variable without synchronization can cause lost updates.
✗ Incorrect
Because counter += 1 is not atomic, some increments can be lost due to race conditions, so the final value is less than 2000.
❓ Predict Output
advanced2: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"
Attempts:
2 left
💡 Hint
By default, unhandled exceptions in threads cause the whole program to terminate.
✗ Incorrect
Ruby raises the exception in the thread, which is not rescued, causing the thread to die silently while the main thread continues.
🧠 Conceptual
expert2:00remaining
Thread synchronization with Mutex
Why is using a Mutex important when multiple threads modify a shared variable?
Attempts:
2 left
💡 Hint
Think about how to avoid two threads changing the same data at the same time.
✗ Incorrect
Mutex locks ensure only one thread can access the shared variable at once, preventing data corruption from race conditions.