Last active
August 29, 2015 14:13
-
-
Save rklemme/10f36380ab5899911b5d to your computer and use it in GitHub Desktop.
Data structure where only one thread is allowed to write
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
class MichaelsLock | |
def initialize | |
@mx = Mutex.new | |
end | |
def lock_writer | |
@mx.synchronize do | |
raise "Already locked" if @writer | |
@writer = Thread.current | |
end | |
end | |
def unlock_writer | |
@mx.synchronize do | |
ensure_this_writes | |
@writer = nil | |
end | |
end | |
# Transaction: do writer lock, yield, release writer lock | |
def writer_work | |
lock_writer | |
begin | |
yield | |
ensure | |
unlock_writer | |
end | |
end | |
def data=(d) | |
@mx.synchronize do | |
ensure_this_writes | |
@data = d | |
end | |
end | |
def data | |
@mx.synchronize do | |
@data | |
end | |
end | |
private | |
# lock must be held - otherwise we need a Monitor and have to lock | |
# here as well | |
def ensure_this_writes | |
raise "Not writer thread" unless @writer == Thread.current | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment