Created
July 4, 2009 09:29
-
-
Save grk/140514 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'thread' | |
class ReadWriteLock | |
def initialize | |
@critical_section = Mutex.new | |
@are_writers_finished = ConditionVariable.new | |
@are_readers_finished = ConditionVariable.new | |
@readers = 0 | |
@writers = 0 | |
@writer_locked = false | |
end | |
def read | |
begin | |
start_read | |
yield | |
ensure | |
end_read | |
end | |
end | |
def start_read | |
@critical_section.lock | |
while (@writers != 0 || @writer_locked) | |
@are_writers_finished.wait(@critical_section) | |
end | |
@readers += 1 | |
@critical_section.unlock | |
end | |
def end_read | |
@critical_section.lock | |
if (@readers -= 1) == 0 | |
@are_readers_finished.broadcast | |
end | |
@critical_section.unlock | |
end | |
def write | |
begin | |
start_write | |
yield | |
ensure | |
end_write | |
end | |
end | |
def start_write | |
@critical_section.lock | |
@writers += 1 | |
while @readers > 0 | |
@are_readers_finished.wait(@critical_section) | |
end | |
while @writer_locked | |
@are_writers_finished.wait(@critical_section) | |
end | |
@writers -= 1 | |
@writer_locked = true | |
@critical_section.unlock | |
end | |
def end_write | |
@critical_section.lock | |
@writer_locked = false | |
@are_writers_finished.broadcast | |
@critical_section.unlock | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment