Project

General

Profile

Actions

Feature #17323

closed

Ractor::LVar to provide ractor-local storage

Added by ko1 (Koichi Sasada) over 3 years ago. Updated about 3 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:100816]

Description

Ruby supports thread and fiber local storage:

  • Thread#[sym] provides Fiber local storage
  • Thread#thread_variable_get(sym)

These APIs can access other threads/fibers like that:

th = Thread.new{
  Thread.current.thread_variable_set(:a, 10)
}
th.join
# access from main thread to child thread
p th.thread_variable_get(:a)

To make Ractor local storage, this kind of feature should not be allowed to protect isolation.

This ticket propose alternative API Ractor::LVar that allows to provide Ractor local variable.

LV1 = Ractor::LVar.new

p LV1.value #=> nil # default value
LV1.value = 'hello' # can set unshareable objects because LVar is ractor local.

Ractor.new do
  LV1.value = 'world' # set Ractor local variable
end.take

p LV1.value #=> 'hello'


# Lvar.new can accept default_proc which should be isolated Proc.

LV2 = Ractor::LVar.new{ "x" * 4 }
p LV2.value #=> "xxxx"
LV2.value = 'yyy'

Ractor.new do
  p LV2.value #=> 'xxx'
end

p LV2.value #=> 'yyy'

This API doesn't support accessing from other ractors.

Ractor::LVar is from Ractor::TVar, but I have no strong opinion about it.
For example, Ractor::LocalVariable is longer and clearer.

Implementation: https://github.com/ruby/ruby/pull/3762

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0