Project

General

Profile

Actions

Feature #19078

closed

Introduce `Fiber#storage` for inheritable fiber-scoped variables.

Added by ioquatix (Samuel Williams) about 2 years ago. Updated almost 2 years ago.

Status:
Closed
Target version:
-
[ruby-core:110481]

Description

Pull Request: https://github.com/ruby/ruby/pull/6612

This is an evolution of the previous ideas:

This PR introduces fiber scoped variables, and is a solution for problems like https://github.com/ioquatix/ioquatix/discussions/17.

The main interface is:

Fiber[key] = value
Fiber[key] # => value

The variables are scoped (local to) a fiber and inherited into child fibers and threads.

Fiber[:request_id] = SecureRandom.hex(16)

Fiber.new do
  p Fiber[:request_id] # prints the above request id
end

The fiber scoped variables are stored and can be accessed:

Fiber.current.storage # => returns a Hash (copy) of the internal storage.
Fiber.current.storage= # => assigns a Hash (copy) to the internal storage.

Fiber itself has one new keyword argument:

Fiber.new(..., storage: hash, false, undef, nil)

This can control how the fiber variables are setup in a child context.

To minimise the performance overhead of some of the implementation choices, we are also simultaneously implementing https://bugs.ruby-lang.org/issues/19077.

Examples

Request loop

Thread.new do
  while request = queue.pop
    Fiber.new(storage: {id: SecureRandom.hex(16)}) do
      handle_request.call(request)
    end
  end
end

OR

Thread.new do
  while request = queue.pop
    Fiber.current.storage = {id: SecureRandom.hex(16)}
    handle_request.call(request)
  end
end

Related issues 3 (1 open2 closed)

Related to Ruby master - Feature #19058: Introduce `Fiber.inheritable` attributes/variables for dealing with shared state.Closedioquatix (Samuel Williams)Actions
Related to Ruby master - Feature #19062: Introduce `Fiber#locals` for shared inheritable state.Closedioquatix (Samuel Williams)Actions
Related to Ruby master - Feature #19141: Add thread-owned Monitor to protect thread-local resourcesOpenActions
Actions

Also available in: Atom PDF

Like3
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like1Like0Like1Like0Like0Like0Like0Like0Like1Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0