Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new Mutex object.
Ruby
mutex = [1].new Drag options to blanks, or click blank then click option'
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
✗ Incorrect
The Mutex.new creates a new mutex object used for thread synchronization.
2fill in blank
mediumComplete 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'
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
✗ Incorrect
The synchronize method locks the mutex, runs the block, then unlocks it automatically.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling lock twice without unlock
Using synchronize without a block
Using wait which is not a Mutex method
✗ Incorrect
After calling lock, you must call unlock to release the mutex.
4fill in blank
hardFill 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'
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
✗ Incorrect
Use synchronize to lock the mutex during increment, and += to add 1 to the counter.
5fill in blank
hardFill 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'
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
✗ Incorrect
Use synchronize to lock the mutex, += to increment, and join to wait for threads to finish.