A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/ThreadLocalVar.html below:

Class: Concurrent::ThreadLocalVar — Concurrent Ruby

Class: Concurrent::ThreadLocalVar
Inherits:
Object show all
Defined in:
lib/concurrent-ruby/concurrent/atomic/thread_local_var.rb
Overview

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

This is similar to Ruby's built-in thread-local variables (Thread#thread_variable_get), but with these major advantages:

Thread-safe Variable Classes

Each of the thread-safe variable classes is designed to solve a different problem. In general:

Constant Summary collapse
LOCALS =
ThreadLocals.new
Instance Method Summary collapse Constructor Details #initialize(default = nil, &default_block) ⇒ ThreadLocalVar

Creates a thread local variable.

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/concurrent-ruby/concurrent/atomic/thread_local_var.rb', line 51

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
Instance Method Details #bind(value) { ... } ⇒ Object

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

88
89
90
91
92
93
94
95
96
97
98
# File 'lib/concurrent-ruby/concurrent/atomic/thread_local_var.rb', line 88

def bind(value)
  if block_given?
    old_value = self.value
    self.value = value
    begin
      yield
    ensure
      self.value = old_value
    end
  end
end
#value ⇒ Object

Returns the value in the current thread's copy of this thread-local variable.

70
71
72
# File 'lib/concurrent-ruby/concurrent/atomic/thread_local_var.rb', line 70

def value
  LOCALS.fetch(@index) { default }
end
#value=(value) ⇒ Object

Sets the current thread's copy of this thread-local variable to the specified value.

78
79
80
# File 'lib/concurrent-ruby/concurrent/atomic/thread_local_var.rb', line 78

def value=(value)
  LOCALS.set(@index, value)
end

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4