Class: Blodsband::Riak::Lock
- Inherits:
-
Object
- Object
- Blodsband::Riak::Lock
- Defined in:
- lib/blodsband/riak/lock.rb
Instance Attribute Summary collapse
-
#key ⇒ Object
readonly
Returns the value of attribute key.
Instance Method Summary collapse
-
#initialize(bucket, key) ⇒ Lock
constructor
Create a new lock in a bucket.
-
#lock(timeout = 1 << 256) ⇒ true, false
Lock this lock, with an optional timeout.
-
#synchronize(&block) ⇒ Object
Execute a block while exclusively locking this lock.
-
#unlock ⇒ Object
Unlock this lock.
Constructor Details
#initialize(bucket, key) ⇒ Lock
Create a new lock in a bucket.
16 17 18 19 |
# File 'lib/blodsband/riak/lock.rb', line 16 def initialize(bucket, key) @bucket = bucket @key = key end |
Instance Attribute Details
#key ⇒ Object (readonly)
Returns the value of attribute key.
8 9 10 |
# File 'lib/blodsband/riak/lock.rb', line 8 def key @key end |
Instance Method Details
#lock(timeout = 1 << 256) ⇒ true, false
Lock this lock, with an optional timeout
28 29 30 31 32 33 34 35 36 37 |
# File 'lib/blodsband/riak/lock.rb', line 28 def lock(timeout = 1 << 256) deadline = Time.now.to_f + timeout while !@bucket.put_if_missing(key, "locked") EM::Synchrony.sleep(0.1) if Time.now.to_f > deadline return false end end return true end |
#synchronize(&block) ⇒ Object
Execute a block while exclusively locking this lock.
55 56 57 58 59 60 61 62 |
# File 'lib/blodsband/riak/lock.rb', line 55 def synchronize(&block) lock begin yield ensure unlock end end |
#unlock ⇒ Object
Unlock this lock
42 43 44 45 46 47 48 |
# File 'lib/blodsband/riak/lock.rb', line 42 def unlock @bucket.delete(key, :riak_params => {:w => :all}) while !@bucket.get(key, :unique => true).nil? EM::Synchrony.sleep(0.1) @bucket.delete(key, :riak_params => {:w => :all}) end end |