about summary refs log tree commit homepage
path: root/lib/tdb/mt.rb
blob: 6742cc40468d9400b89246f199322074ba67af76 (plain)
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
# -*- encoding: binary -*-
module TDB::MT
  def initialize
    super
    @lock = Mutex.new
  end

  %w(
    close closed? fetch [] store []= insert! modify! insert modify
    key? has_key? include? member?
    nuke! delete
    lockall trylockall unlockall
    lockall_read trylockall_read unlockall_read
    lockall_mark lockall_unmark
  ).each do |meth|
    eval "def #{meth}(*args); @lock.synchronize { super }; end"
  end

  def each(&block)
    @lock.synchronize do
      super { |k,v| @lock.exclusive_unlock { yield(k,v) } }
    end
  end

  def threadsafe?
    true
  end

  def self.extended(obj)
    obj.instance_eval { @lock = Mutex.new unless defined?(@lock) }
  end

  def self.included(klass)
    ObjectSpace.each_object(klass) { |obj|
      obj.instance_eval { @lock = Mutex.new unless defined?(@lock) }
    }
  end
end