mirror of
https://github.com/discourse/discourse.git
synced 2025-05-22 07:53:49 +08:00
Tighten API, add spec for recovery, keep mutex semantics
This commit is contained in:
@ -3,34 +3,47 @@ require_dependency 'distributed_mutex'
|
||||
|
||||
describe DistributedMutex do
|
||||
it "allows only one mutex object to have the lock at a time" do
|
||||
m1 = DistributedMutex.new("test_mutex_key")
|
||||
m2 = DistributedMutex.new("test_mutex_key")
|
||||
|
||||
m1.get_lock
|
||||
m2.got_lock.should be_false
|
||||
|
||||
t = Thread.new do
|
||||
m2.get_lock
|
||||
mutexes = (1..10).map do
|
||||
DistributedMutex.new("test_mutex_key")
|
||||
end
|
||||
|
||||
m1.release_lock
|
||||
t.join
|
||||
m2.got_lock.should == true
|
||||
end
|
||||
|
||||
it "synchronizes correctly" do
|
||||
array = []
|
||||
t = Thread.new do
|
||||
DistributedMutex.new("correct_sync").synchronize do
|
||||
sleep 0.01
|
||||
array.push 1
|
||||
x = 0
|
||||
mutexes.map do |m|
|
||||
Thread.new do
|
||||
m.synchronize do
|
||||
y = x
|
||||
sleep 0.001
|
||||
x = y + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
sleep 0.005
|
||||
DistributedMutex.new("correct_sync").synchronize do
|
||||
array.push 2
|
||||
end
|
||||
t.join
|
||||
array.should == [1, 2]
|
||||
end.map(&:join)
|
||||
|
||||
x.should == 10
|
||||
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
|
||||
|
Reference in New Issue
Block a user