Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Thread#thread_variable_get
thr.thread_variable_get(key) → obj or nil
thread.c
View on GitHub ↗
static VALUE
rb_thread_variable_get(VALUE thread, VALUE key)
{
VALUE locals;
if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
return Qnil;
}
locals = rb_thread_local_storage(thread);
return rb_hash_aref(locals, rb_to_symbol(key));
}
Returns the value of a thread local variable that has been set. Note that these are different than fiber local values. For fiber local values, please see Thread#[] and Thread#[]=.
Thread local values are carried along with threads, and do not respect fibers. For example:
Example
Thread.new { Thread.current.thread_variable_set("foo", "bar") # set a thread local Thread.current["foo"] = "bar" # set a fiber local Fiber.new { Fiber.yield [ Thread.current.thread_variable_get("foo"), # get the thread local Thread.current["foo"], # get the fiber local ] }.resume }.join.value # => ['bar', nil]
The value “bar” is returned for the thread local, where nil is returned for the fiber local. The fiber is executed in the same thread, so the thread local values are available.
See also
#thread_variable?
#thread_variables
#terminate
#thread_variable_set
also in
4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0