From 02bf7af7257d5df14a3b3add7cbf584208d53aca Mon Sep 17 00:00:00 2001 From: Eugen Kuksa Date: Sat, 9 Jul 2016 10:30:47 +0200 Subject: [PATCH] Recognize lock state of other semaphores with the same key. --- lib/redis/semaphore.rb | 2 +- spec/semaphore_spec.rb | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/redis/semaphore.rb b/lib/redis/semaphore.rb index 461fa72..8f77d16 100644 --- a/lib/redis/semaphore.rb +++ b/lib/redis/semaphore.rb @@ -94,7 +94,7 @@ def locked?(token = nil) if token @redis.hexists(grabbed_key, token) else - @tokens.each do |token| + all_tokens.each do |token| return true if locked?(token) end diff --git a/spec/semaphore_spec.rb b/spec/semaphore_spec.rb index e2c0d65..7d59966 100644 --- a/spec/semaphore_spec.rb +++ b/spec/semaphore_spec.rb @@ -43,6 +43,15 @@ expect(semaphore.locked?).to eq(false) end + it "recognizes the lock state of another semaphore with the same key" do + semaphore.lock(1) + expect(semaphore.locked?).to eq(true) + expect(semaphore2.locked?).to eq(true) + semaphore.unlock + expect(semaphore.locked?).to eq(false) + expect(semaphore2.locked?).to eq(false) + end + it "should not lock twice as a mutex" do expect(semaphore.lock(1)).not_to eq(false) expect(semaphore.lock(1)).to eq(false) @@ -147,6 +156,7 @@ describe "semaphore with expiration" do let(:semaphore) { Redis::Semaphore.new(:my_semaphore, :redis => @redis, :expiration => 2) } + let(:semaphore2) { Redis::Semaphore.new(:my_semaphore, :redis => @redis, :expiration => 2) } let(:multisem) { Redis::Semaphore.new(:my_semaphore_2, :resources => 2, :redis => @redis, :expiration => 2) } it_behaves_like "a semaphore" @@ -170,6 +180,7 @@ describe "semaphore without staleness checking" do let(:semaphore) { Redis::Semaphore.new(:my_semaphore, :redis => @redis) } + let(:semaphore2) { Redis::Semaphore.new(:my_semaphore, :redis => @redis) } let(:multisem) { Redis::Semaphore.new(:my_semaphore_2, :resources => 2, :redis => @redis) } it_behaves_like "a semaphore" @@ -208,6 +219,7 @@ describe "semaphore with staleness checking" do let(:semaphore) { Redis::Semaphore.new(:my_semaphore, :redis => @redis, :stale_client_timeout => 5) } + let(:semaphore2) { Redis::Semaphore.new(:my_semaphore, :redis => @redis, :stale_client_timeout => 5) } let(:multisem) { Redis::Semaphore.new(:my_semaphore_2, :resources => 2, :redis => @redis, :stale_client_timeout => 5) } it_behaves_like "a semaphore"