File: lock.rb

package info (click to toggle)
ruby-moneta 1.6.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,776 kB
  • sloc: ruby: 13,201; sh: 178; makefile: 7
file content (45 lines) | stat: -rw-r--r-- 888 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
require 'set'

module Moneta
  # Locks the underlying stores with a Mutex
  # @api public
  class Lock < Wrapper
    # @param [Moneta store] adapter The underlying store
    # @param [Hash] options
    # @option options [String] :mutex (::Mutex.new) Mutex object
    def initialize(adapter, options = {})
      super
      @lock = options[:mutex] || ::Mutex.new
    end

    protected

    def wrap(name, *args, &block)
      self.locks ||= Set.new
      if locked?
        yield
      else
        lock!(&block)
      end
    end

    def locks=(locks)
      Thread.current.thread_variable_set('Moneta::Lock', locks)
    end

    def locks
      Thread.current.thread_variable_get('Moneta::Lock')
    end

    def lock!(&block)
      locks << @lock
      @lock.synchronize(&block)
    ensure
      locks.delete @lock
    end

    def locked?
      locks.include? @lock
    end
  end
end