0
0
Rubyprogramming~10 mins

Thread safety concepts in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a new thread in Ruby.

Ruby
thread = Thread.[1] do
  puts 'Hello from thread'
end
thread.join
Drag options to blanks, or click blank then click option'
Astart
Bnew
Ccreate
Drun
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'start' instead of 'new' to create a thread.
Using 'create' or 'run' which are not valid Thread methods.
2fill in blank
medium

Complete the code to safely increment a shared counter using a Mutex.

Ruby
mutex = Mutex.new
counter = 0

mutex.[1] do
  counter += 1
end
Drag options to blanks, or click blank then click option'
Await
Bacquire
Clock
Dsynchronize
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'lock' without unlocking the mutex.
Using 'acquire' or 'wait' which are not Ruby Mutex methods.
3fill in blank
hard

Fix the error in the code to avoid race conditions when updating the shared variable.

Ruby
mutex = Mutex.new
count = 0
threads = []
5.times do
  threads << Thread.new do
    [1].synchronize do
      count += 1
    end
  end
end
threads.each(&:join)
puts count
Drag options to blanks, or click blank then click option'
Amutex
Bcount
Cself
DThread
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to synchronize on the shared variable itself.
Using Thread or self which do not provide locking.
4fill in blank
hard

Fill both blanks to create a thread-safe hash using a Mutex.

Ruby
mutex = Mutex.new
safe_hash = {}

threads = 3.times.map do
  Thread.new do
    mutex.[1] do
      safe_hash[[2]] = 'value'
    end
  end
end
threads.each(&:join)
Drag options to blanks, or click blank then click option'
Asynchronize
Bkey
C:key
Dlock
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'lock' instead of 'synchronize' for mutex.
Using a variable 'key' without defining it.
5fill in blank
hard

Fill all three blanks to safely update a shared array in multiple threads.

Ruby
mutex = Mutex.new
shared_array = []
threads = []

5.times do |i|
  threads << Thread.new do
    mutex.[1] do
      shared_array.[2](i)
    end
  end
end
threads.each(&:join)

puts shared_array.[3]
Drag options to blanks, or click blank then click option'
Asynchronize
Bpush
Csort
Dlock
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'lock' instead of 'synchronize' for mutex.
Using 'append' instead of 'push' for arrays.
Not sorting the array before printing.