Class: ThreadLocal

Inherits:
Object
  • Object
show all
Defined in:
lib/thread_local.rb,
lib/thread_local/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Constructor Details

#initialize(initial_value, *args) ⇒ ThreadLocal

Returns a new instance of ThreadLocal.



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/thread_local.rb', line 6

def initialize(initial_value, *args)
  opts, = args

  opts ||= {}

  @initial_value = to_callable(initial_value)
  @prefix = opts[:prefix] || 'thread_local'

  @threads_mutex = Mutex.new
  @threads = Set.new

  define_initializer!
end

Instance Method Details

#__threads_object_ids__Object



60
61
62
# File 'lib/thread_local.rb', line 60

def __threads_object_ids__
  @threads
end

#deleteObject



50
51
52
53
54
55
56
57
58
# File 'lib/thread_local.rb', line 50

def delete
  t = Thread.current

  t.thread_variable_set value_key, nil

  @threads_mutex.synchronize do
    @threads.delete(t.object_id)
  end
end

#getObject



20
21
22
23
24
25
26
27
28
# File 'lib/thread_local.rb', line 20

def get
  t = Thread.current

  if set?
    t.thread_variable_get value_key
  else
    set @initial_value.call
  end
end

#set(new_value) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/thread_local.rb', line 35

def set(new_value)
  t = Thread.current

  t.thread_variable_set value_key, new_value
  t.thread_variable_set value_initialized_key, true

  forget_vanished_threads!

  @threads_mutex.synchronize do
    @threads.add(t.object_id)
  end

  new_value
end

#set?Boolean

Returns:

  • (Boolean)


30
31
32
33
# File 'lib/thread_local.rb', line 30

def set?
  t = Thread.current
  t.thread_variable_get value_initialized_key
end