Challenge - 5 Problems
Thread Safety Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of thread increment without synchronization
What is the output of this Ruby code that increments a shared counter from multiple threads without any synchronization?
Ruby
counter = 0 threads = [] 10.times do threads << Thread.new do 1000.times { counter += 1 } end end threads.each(&:join) puts counter
Attempts:
2 left
💡 Hint
Think about what happens when multiple threads update the same variable without locks.
✗ Incorrect
Because the increment operation is not atomic, some increments can be lost due to race conditions, so the final counter is usually less than 10000.
🧠 Conceptual
intermediate1:30remaining
Understanding Mutex usage in Ruby
Why do we use a Mutex in Ruby when working with threads?
Attempts:
2 left
💡 Hint
Think about what happens if two threads try to change the same data at once.
✗ Incorrect
A Mutex ensures that only one thread can access a shared resource at a time, preventing race conditions.
🔧 Debug
advanced2:30remaining
Identify the cause of inconsistent output in threaded code
This Ruby code uses threads to append to an array. Why might the final array length be less than expected?
Ruby
arr = [] threads = [] 5.times do threads << Thread.new do 100.times { arr << 1 } end end threads.each(&:join) puts arr.length
Attempts:
2 left
💡 Hint
Consider if appending to an array is safe when multiple threads do it at once.
✗ Incorrect
Appending to an array is not thread-safe in Ruby, so concurrent appends can overwrite or lose data, causing fewer elements than expected.
📝 Syntax
advanced2:00remaining
Identify the syntax error in thread synchronization code
Which option contains a syntax error in Ruby code that uses a Mutex to synchronize threads?
Ruby
mutex = Mutex.new counter = 0 threads = [] 10.times do threads << Thread.new do mutex.synchronize do counter += 1 end end end threads.each(&:join) puts counter
Attempts:
2 left
💡 Hint
Check the syntax of the block passed to synchronize.
✗ Incorrect
Option A is missing the 'do' keyword before the block and has an extra 'end', causing a syntax error.
🚀 Application
expert3:00remaining
Determine the final value of a shared variable with thread-safe increments
Given this Ruby code using a Mutex to safely increment a shared counter from multiple threads, what is the final value of counter?
Ruby
counter = 0 mutex = Mutex.new threads = [] 20.times do threads << Thread.new do 500.times do mutex.synchronize { counter += 1 } end end end threads.each(&:join) puts counter
Attempts:
2 left
💡 Hint
Mutex ensures increments happen one at a time without loss.
✗ Incorrect
Mutex synchronization prevents race conditions, so all increments are counted, resulting in 20 * 500 = 10000.