Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lock_expiration splitting character changed to ';' with some tests #10

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions lib/redis/lock.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def lock(key, timeout = 60, max_attempts = 100)
return true
else
current_lock = self.get(current_lock_key)
if (current_lock.to_s.split('-').first.to_i) < Time.now.to_i
if (current_lock.to_s.split(';').first.to_i) < Time.now.to_i
compare_value = self.getset(current_lock_key, expiration_value)
return true if compare_value == current_lock
end
Expand All @@ -62,7 +62,7 @@ def unlock(key)
current_lock_key = lock_key(key)
lock_value = self.get(current_lock_key)
return true unless lock_value
lock_timeout, lock_process, lock_thread = lock_value.split('-')
lock_timeout, lock_process, lock_thread = lock_value.split(';')
if (lock_timeout.to_i > Time.now.to_i) && (lock_process.to_i == Process.pid) && lock_thread.to_i == Thread.current.object_id
self.del(current_lock_key)
return true
Expand All @@ -74,7 +74,7 @@ def unlock(key)
private

def lock_expiration(timeout)
"#{Time.now.to_i + timeout + 1}-#{Process.pid}-#{Thread.current.object_id}"
"#{Time.now.to_i + timeout + 1};#{Process.pid};#{Thread.current.object_id}"
end

def lock_key(key)
Expand Down
11 changes: 11 additions & 0 deletions spec/redis_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,5 +65,16 @@
# Should have spent 1 second trying to lock
DateTime.now.should >= time + Rational(1, 86400)
end

it "should not unlock a key from another thread" do
@redis.lock('test_key').should be_true
Thread.new { @redis.unlock('test_key').should_not be_true }.join
end

it "should not unlock a key from another process" do
fork { @redis.lock('test_key'); exit 0 }
Process.wait2
@redis.unlock('test_key').should_not be_true
end

end