Beta

Re-entrant Mutex (aka Counting Mutex)

Description:

Implement a re-entrant mutex class RMutex that has the following methods:

  • acquire:
    • if the mutex is acquired by some other thread, wait until it is released
    • if the mutex is free, acquire it and set the counter to 1
    • if the mutex is already acquired by the current thread, increment the counter
  • release:
    • if the mutex is not acquired by the current thread, raise an error
    • if the mutex is acquired by the current thread, decrement the counter; if the counter reaches 0, release the mutex.
  • counter: get the current counter
  • owner: get the thread that is holding the mutex or nil if it is released

Initially, the re-entrant mutex must be in the released state.

The following code illustrates the expected behavior:

mx = RMutex.new

mx.owner # => nil
mx.counter # => 0

mx.acquire # => returns immediately, acquire, counter: 0 -> 1
mx.acquire # => returns immediately, counter: 1 -> 2

mx.owner # => Thread.current
mx.counter # => 2

mx.release # => counter: 2 -> 1

mx.owner # => Thread.current
mx.counter # => 1

other_thread = Thread.new do 
  mx.acquire
  puts "Acquired" 
  sleep 20 
  mx.release
end
sleep 1
# other_thread waits on the mutex

mx.release # => counter: 1 -> 0, release
# at this moment other_thread wakes up and prints "Acquired"

mx.owner # => other_thread
mx.counter # => 1

mx.acquire # hangs, waiting until other_thread releases the mutex
# after other_thread sleeps for 20 seconds, the execution of the current thread continues



Threads
Fundamentals

More By Author:

Check out these other kata created by moonfly

Stats:

CreatedSep 25, 2014
PublishedSep 25, 2014
Warriors Trained115
Total Skips79
Total Code Submissions95
Total Times Completed11
Ruby Completions11
Total Stars3
% of votes with a positive feedback rating75% of 2
Total "Very Satisfied" Votes1
Total "Somewhat Satisfied" Votes1
Total "Not Satisfied" Votes0
Total Rank Assessments3
Average Assessed Rank
6 kyu
Highest Assessed Rank
5 kyu
Lowest Assessed Rank
7 kyu
Ad
Contributors
  • moonfly Avatar
Ad