[]

thr[sym] â obj or nil
Instance Public methods

Attribute ReferenceâReturns the value of a fiber-local variable (current thread's root fiber if not explicitely inside a Fiber), using either a symbol or a string name. If the specified variable does not exist, returns nil.

[
  Thread.new { Thread.current["name"] = "A" },
  Thread.new { Thread.current[:name]  = "B" },
  Thread.new { Thread.current["name"] = "C" }
].each do |th|
  th.join
  puts "#{th.inspect}: #{th[:name]}"
end

produces:

#<Thread:0x00000002a54220 dead>: A
#<Thread:0x00000002a541a8 dead>: B
#<Thread:0x00000002a54130 dead>: C

#[] and #[]= are not thread-local but fiber-local. This confusion did not exist in Ruby 1.8 because fibers were only available since Ruby 1.9. Ruby 1.9 chooses that the methods behaves fiber-local to save following idiom for dynamic scope.

def meth(newvalue)
  begin
    oldvalue = Thread.current[:name]
    Thread.current[:name] = newvalue
    yield
  ensure
    Thread.current[:name] = oldvalue
  end
end

The idiom may not work as dynamic scope if the methods are thread-local and a given block switches fiber.

f = Fiber.new {
  meth(1) {
    Fiber.yield
  }
}
meth(2) {
  f.resume
}
f.resume
p Thread.current[:name]
#=> nil if fiber-local
#=> 2 if thread-local (The value 2 is leaked to outside of meth method.)

For thread-local variables, please see Thread#thread_local_get and Thread#thread_local_set.

doc_ruby_on_rails
2015-05-17 12:40:56
Comments
Leave a Comment

Please login to continue.