Tighten API, add spec for recovery, keep mutex semantics

This commit is contained in:
Sam 2014-04-14 10:51:46 +10:00
parent 0f2312a97e
commit 63f4a0e050
2 changed files with 67 additions and 57 deletions

View File

@ -1,51 +1,48 @@
# Cross-process locking using Redis. # Cross-process locking using Redis.
class DistributedMutex class DistributedMutex
attr_accessor :redis
attr_reader :got_lock
def initialize(key, redis=nil) def initialize(key, redis=nil)
@key = key @key = key
@redis = redis || $redis @redis = redis || $redis
@got_lock = false @mutex = Mutex.new
end end
# NOTE wrapped in mutex to maintain its semantics
def synchronize
@mutex.lock
while !try_to_get_lock
sleep 0.001
end
yield
ensure
@redis.del @key
@mutex.unlock
end
private
def try_to_get_lock def try_to_get_lock
if redis.setnx @key, Time.now.to_i + 60 got_lock = false
redis.expire @key, 60 if @redis.setnx @key, Time.now.to_i + 60
@got_lock = true @redis.expire @key, 60
got_lock = true
else else
begin begin
redis.watch @key @redis.watch @key
time = redis.get @key time = @redis.get @key
if time && time.to_i < Time.now.to_i if time && time.to_i < Time.now.to_i
@got_lock = redis.multi do got_lock = @redis.multi do
redis.set @key, Time.now.to_i + 60 @redis.set @key, Time.now.to_i + 60
end end
end end
ensure ensure
redis.unwatch @redis.unwatch
end end
end end
got_lock
end end
def get_lock
return if @got_lock
start = Time.now
while !@got_lock
try_to_get_lock
end
end
def release_lock
redis.del @key
@got_lock = false
end
def synchronize
get_lock
yield
ensure
release_lock
end
end end

View File

@ -3,34 +3,47 @@ require_dependency 'distributed_mutex'
describe DistributedMutex do describe DistributedMutex do
it "allows only one mutex object to have the lock at a time" do it "allows only one mutex object to have the lock at a time" do
m1 = DistributedMutex.new("test_mutex_key") mutexes = (1..10).map do
m2 = DistributedMutex.new("test_mutex_key") DistributedMutex.new("test_mutex_key")
m1.get_lock
m2.got_lock.should be_false
t = Thread.new do
m2.get_lock
end end
m1.release_lock x = 0
t.join mutexes.map do |m|
m2.got_lock.should == true Thread.new do
end m.synchronize do
y = x
it "synchronizes correctly" do sleep 0.001
array = [] x = y + 1
t = Thread.new do end
DistributedMutex.new("correct_sync").synchronize do
sleep 0.01
array.push 1
end end
end end.map(&:join)
sleep 0.005
DistributedMutex.new("correct_sync").synchronize do x.should == 10
array.push 2
end
t.join
array.should == [1, 2]
end end
it "handles auto cleanup correctly" do
m = DistributedMutex.new("test_mutex_key")
$redis.setnx "test_mutex_key", Time.now.to_i - 1
start = Time.now.to_i
m.synchronize do
"nop"
end
# no longer than a second
Time.now.to_i.should <= start + 1
end
it "maintains mutex semantics" do
m = DistributedMutex.new("test_mutex_key")
lambda {
m.synchronize do
m.synchronize{}
end
}.should raise_error(ThreadError)
end
end end