Module: DSLKit::ThreadLocal

Included in:
Deflect, Object
Defined in:
lib/dslkit/polite.rb

Constant Summary collapse

@@mutex =
Mutex.new
@@cleanup =
lambda do |my_object_id|
  my_id = "__thread_local_#{my_object_id}__"
  @@mutex.synchronize do
    for t in Thread.list
      t[my_id] = nil if t[my_id]
    end
  end
end

Instance Method Summary collapse

Instance Method Details

#instance_thread_local(name, value = nil) ⇒ Object

Define a thread local variable for the current instance with name name. If the value value is given, it is used to initialize the variable.



97
98
99
100
101
102
103
104
# File 'lib/dslkit/polite.rb', line 97

def instance_thread_local(name, value = nil)
  sc = class << self
    extend DSLKit::ThreadLocal
    self
  end
  sc.thread_local name, value
  self
end

#thread_local(name, default_value = nil) ⇒ Object

Define a thread local variable named name in this module/class. If the value value is given, it is used to initialize the variable.



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/dslkit/polite.rb', line 70

def thread_local(name, default_value = nil)
  is_a?(Module) or raise TypeError, "receiver has to be a Module"

  name = name.to_s
  my_id = "__thread_local_#{__id__}__"

  ObjectSpace.define_finalizer(self, @@cleanup)

  define_method(name) do
    Thread.current[my_id] ||= {}
    Thread.current[my_id][name]
  end

  define_method("#{name}=") do |value|
    Thread.current[my_id] ||= {}
    Thread.current[my_id][name] = value
  end

  if default_value
    Thread.current[my_id] = {}
    Thread.current[my_id][name] = default_value
  end
  self
end