Fiber#storage=
static VALUE
rb_fiber_storage_set(VALUE self, VALUE value)
{
if (rb_warning_category_enabled_p(RB_WARN_CATEGORY_EXPERIMENTAL)) {
rb_category_warn(RB_WARN_CATEGORY_EXPERIMENTAL,
"Fiber#storage= is experimental and may be removed in the future!");
}
storage_access_must_be_from_same_fiber(self);
fiber_storage_validate(value);
fiber_ptr(self)->cont.saved_ec.storage = rb_obj_dup(value);
return value;
}
Sets the storage hash for the fiber. This feature is experimental and may change in the future. The method can only be called on the Fiber.current.
You should be careful about using this method as you may inadvertently clear important fiber-storage state. You should mostly prefer to assign specific keys in the storage using Fiber::[]=.
You can also use Fiber.new(storage: nil) to create a fiber with an empty storage.
Example:
while request = request_queue.pop # Reset the per-request state: Fiber.current.storage = nil handle_request(request) end
Ruby version changes
-
3.2
-
Introduce
Fiber.[]andFiber.[]=for inheritable fiber storage. IntroduceFiber#storageandFiber#storage=(experimental) for getting and resetting the current storage. IntroduceFiber.new(storage:)for setting the storage when creating a fiber. [Feature #19078]Existing
ThreadandFiberlocal variables can be tricky to use. Thread-local variables are shared between all fibers, making it hard to isolate, while Fiber-local variables can be hard to share. It is often desirable to define unit of execution (“execution context”) such that some state is shared between all fibers and threads created in that context. This is whatFiberstorage provides.Exampledef log(message) puts "#{Fiber[:request_id]}: #{message}" end def handle_requests while request = read_request Fiber.schedule do Fiber[:request_id] = SecureRandom.uuid request.messages.each do |message| Fiber.schedule do log("Handling #{message}") # Log includes inherited request_id. end end end end end
You should generally consider
Fiberstorage for any state which you want to be shared implicitly between all fibers and threads created in a given context, e.g. a connection pool, a request id, a logger level, environment variables, configuration, etc.
-