class Concurrent::LockLocalVar

A ‘FiberLocalVar` is a variable where the value is different for each fiber. Each variable may have a default value, but when you modify the variable only the current fiber will ever see that change.

This is similar to Ruby’s built-in fiber-local variables (‘Thread.current`), but with these major advantages:

@example

v = FiberLocalVar.new(14)
v.value #=> 14
v.value = 2
v.value #=> 2

@example

v = FiberLocalVar.new(14)

Fiber.new do
  v.value #=> 14
  v.value = 1
  v.value #=> 1
end.resume

Fiber.new do
  v.value #=> 14
  v.value = 2
  v.value #=> 2
end.resume

v.value #=> 14

Either {FiberLocalVar} or {ThreadLocalVar} depending on whether Mutex (and Monitor) are held, respectively, per Fiber or per Thread.

Constants

LOCALS

Public Class Methods

new(default = nil, &default_block) click to toggle source

Creates a fiber local variable.

@param [Object] default the default value when otherwise unset @param [Proc] default_block Optional block that gets called to obtain the

default value for each fiber
# File lib/concurrent-ruby/concurrent/atomic/fiber_local_var.rb, line 49
def initialize(default = nil, &default_block)
  if default && block_given?
    raise ArgumentError, "Cannot use both value and block as default value"
  end

  if block_given?
    @default_block = default_block
    @default = nil
  else
    @default_block = nil
    @default = default
  end

  @index = LOCALS.next_index(self)
end

Public Instance Methods

bind(value) { || ... } click to toggle source

Bind the given value to fiber local storage during execution of the given block.

@param [Object] value the value to bind @yield the operation to be performed with the bound variable @return [Object] the value

# File lib/concurrent-ruby/concurrent/atomic/fiber_local_var.rb, line 86
def bind(value)
  if block_given?
    old_value = self.value
    self.value = value
    begin
      yield
    ensure
      self.value = old_value
    end
  end
end
value() click to toggle source

Returns the value in the current fiber’s copy of this fiber-local variable.

@return [Object] the current value

# File lib/concurrent-ruby/concurrent/atomic/fiber_local_var.rb, line 68
def value
  LOCALS.fetch(@index) { default }
end
value=(value) click to toggle source

Sets the current fiber’s copy of this fiber-local variable to the specified value.

@param [Object] value the value to set @return [Object] the new value

# File lib/concurrent-ruby/concurrent/atomic/fiber_local_var.rb, line 76
def value=(value)
  LOCALS.set(@index, value)
end

Protected Instance Methods

default() click to toggle source

@!visibility private

# File lib/concurrent-ruby/concurrent/atomic/fiber_local_var.rb, line 101
def default
  if @default_block
    self.value = @default_block.call
  else
    @default
  end
end