0
0
Rubyprogramming~10 mins

Thread synchronization with Mutex 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 Mutex object.

Ruby
mutex = [1].new
Drag options to blanks, or click blank then click option'
AMutex
BThread
CLock
DSync
Attempts:
3 left
💡 Hint
Common Mistakes
Using Thread.new instead of Mutex.new
Using Lock.new which is not a Ruby class
Using Sync.new which does not exist
2fill in blank
medium

Complete the code to lock the mutex before accessing the shared resource.

Ruby
mutex.[1] do
  # critical section
end
Drag options to blanks, or click blank then click option'
Alock
Bsynchronize
Cunlock
Dwait
Attempts:
3 left
💡 Hint
Common Mistakes
Using lock without a block, which requires manual unlock
Using unlock before locking
Using wait which is not a Mutex method
3fill in blank
hard

Fix the error in the code to properly unlock the mutex after locking it.

Ruby
mutex.lock
# critical section
mutex.[1]
Drag options to blanks, or click blank then click option'
Alock
Bwait
Csynchronize
Dunlock
Attempts:
3 left
💡 Hint
Common Mistakes
Calling lock twice without unlock
Using synchronize without a block
Using wait which is not a Mutex method
4fill in blank
hard

Fill both blanks to create a thread-safe increment of a shared counter.

Ruby
counter = 0
mutex = Mutex.new
thread = Thread.new do
  mutex.[1] do
    counter [2] 1
  end
end
thread.join
Drag options to blanks, or click blank then click option'
Asynchronize
B+=
C-=
Dlock
Attempts:
3 left
💡 Hint
Common Mistakes
Using lock without unlock for the first blank
Using -= instead of += for increment
Not locking the mutex at all
5fill in blank
hard

Fill all three blanks to create two threads that safely increment a shared variable.

Ruby
counter = 0
mutex = Mutex.new
threads = []
2.times do
  threads << Thread.new do
    mutex.[1] do
      temp = counter
      temp [2] 1
      counter = temp
    end
  end
end
threads.each(&:[3])
Drag options to blanks, or click blank then click option'
Asynchronize
B+=
Cjoin
Dlock
Attempts:
3 left
💡 Hint
Common Mistakes
Using lock without unlock for the first blank
Using -= instead of += for increment
Not joining threads causing premature program exit