Skip to content

Instantly share code, notes, and snippets.

@rklemme
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rklemme/10f36380ab5899911b5d to your computer and use it in GitHub Desktop.
Save rklemme/10f36380ab5899911b5d to your computer and use it in GitHub Desktop.
Data structure where only one thread is allowed to write
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