class method · added in Ruby 3.4
Ractor.store_if_absent
[A] (::Symbol) { (nil) -> A } -> A
Ractor.store_if_absent(key){ init_block }
ractor.rb
View on GitHub ↗
# File tmp/rubies/ruby-4.0.0/ractor.rb, line 513
def self.store_if_absent(sym)
Primitive.attr! :use_block
Primitive.ractor_local_value_store_if_absent(sym)
end
If the corresponding ractor-local value is not set, yields a value with init_block and stores the value in a thread-safe manner. This method returns the stored value.
Example
(1..10).map{ Thread.new(it){|i| Ractor.store_if_absent(:s){ f(); i } #=> return stored value of key :s } }.map(&:value).uniq.size #=> 1 and f() is called only once
Ruby version changes
-
3.4
-
Ractor.store_if_absent(key){ init }is added to initialize ractor local variables in thread-safety. [Feature #20875]
-