Sha256: 2e906435c25fd73a956f411ceee638196eb6b394370501ac735b3b5b5ab71b8b

Contents?: true

Size: 1.35 KB

Versions: 63

Compression:

Stored size: 1.35 KB

Contents

module Tins
  module ThreadLocal
    @@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

    # Define a thread local variable named _name_ in this module/class. If the
    # value _value_ is given, it is used to initialize the variable.
    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

    # 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.
    def instance_thread_local(name, value = nil)
      class << self
        extend Tins::ThreadLocal
        self
      end.thread_local name, value
      self
    end
  end
end

Version data entries

63 entries across 60 versions & 8 rubygems

Version Path
tdiary-5.0.11 vendor/bundle/gems/tins-1.16.3/lib/tins/thread_local.rb
tins-1.17.0 lib/tins/thread_local.rb
tdiary-5.0.9 vendor/bundle/gems/tins-1.16.3/lib/tins/thread_local.rb
tdiary-5.0.8 vendor/bundle/gems/tdiary-5.0.7/vendor/bundle/gems/tins-1.16.3/lib/tins/thread_local.rb
tdiary-5.0.7 vendor/bundle/gems/tins-1.16.3/lib/tins/thread_local.rb
tins-1.16.3 lib/tins/thread_local.rb
tins-1.16.2 lib/tins/thread_local.rb
tins-1.16.1 lib/tins/thread_local.rb
tins-1.16.0 lib/tins/thread_local.rb
tins-1.15.1 lib/tins/thread_local.rb
tdiary-5.0.6 vendor/bundle/gems/tins-1.15.0/lib/tins/thread_local.rb
logstash-filter-cache-redis-0.3.1 vendor/bundle/jruby/1.9/gems/tins-1.6.0/lib/tins/thread_local.rb
logstash-filter-cache-redis-0.3.0 vendor/bundle/jruby/1.9/gems/tins-1.6.0/lib/tins/thread_local.rb
logstash-filter-cache-redis-0.2.0 vendor/bundle/jruby/1.9/gems/tins-1.6.0/lib/tins/thread_local.rb
logstash-filter-cache-redis-0.1.0 vendor/bundle/jruby/1.9/gems/tins-1.6.0/lib/tins/thread_local.rb
tins-1.15.0 lib/tins/thread_local.rb
tdiary-5.0.5 vendor/bundle/gems/tdiary-5.0.4/vendor/bundle/gems/tins-1.13.2/lib/tins/thread_local.rb
tdiary-5.0.5 vendor/bundle/gems/tins-1.14.0/lib/tins/thread_local.rb
tdiary-5.0.5 vendor/bundle/gems/tins-1.13.2/lib/tins/thread_local.rb
tins-1.14.0 lib/tins/thread_local.rb