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:
ThreadLocalVar
has its own identity, it doesn't need a Symbol.ThreadLocalVar
has no such issue and it is fine to create many of them.ThreadLocalVar
automatically removes the mapping for each thread once the ThreadLocalVar
instance is GC'd.Each of the thread-safe variable classes is designed to solve a different problem. In general:
ThreadLocals.new
Bind the given value to thread local storage during execution of the given block.
Creates a thread local variable.
Returns the value in the current thread's copy of this thread-local variable.
Sets the current thread's copy of this thread-local variable to the specified value.
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) endInstance 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