Beta
Re-entrant Mutex (aka Counting Mutex)
11moonfly
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 counterowner
: get the thread that is holding the mutex ornil
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
Similar Kata:
Stats:
Created | Sep 25, 2014 |
Published | Sep 25, 2014 |
Warriors Trained | 115 |
Total Skips | 79 |
Total Code Submissions | 95 |
Total Times Completed | 11 |
Ruby Completions | 11 |
Total Stars | 3 |
% of votes with a positive feedback rating | 75% of 2 |
Total "Very Satisfied" Votes | 1 |
Total "Somewhat Satisfied" Votes | 1 |
Total "Not Satisfied" Votes | 0 |
Total Rank Assessments | 3 |
Average Assessed Rank | 6 kyu |
Highest Assessed Rank | 5 kyu |
Lowest Assessed Rank | 7 kyu |