Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 75 lines (68 sloc) 2.387 kb
a565f80 @rafaelfranca Backport thread-local variables from Ruby 2.0
rafaelfranca authored
1 class Thread
2 LOCK = Mutex.new # :nodoc:
3
4 # Returns the value of a thread local variable that has been set. Note that
5 # these are different than fiber local values.
6 #
7 # Thread local values are carried along with threads, and do not respect
8 # fibers. For example:
9 #
10 # Thread.new {
11 # Thread.current.thread_variable_set("foo", "bar") # set a thread local
12 # Thread.current["foo"] = "bar" # set a fiber local
13 #
14 # Fiber.new {
15 # Fiber.yield [
16 # Thread.current.thread_variable_get("foo"), # get the thread local
17 # Thread.current["foo"], # get the fiber local
18 # ]
19 # }.resume
20 # }.join.value # => ['bar', nil]
21 #
22 # The value <tt>"bar"</tt> is returned for the thread local, where +nil+ is returned
23 # for the fiber local. The fiber is executed in the same thread, so the
24 # thread local values are available.
25 def thread_variable_get(key)
26 locals[key.to_sym]
27 end
28
29 # Sets a thread local with +key+ to +value+. Note that these are local to
30 # threads, and not to fibers. Please see Thread#thread_variable_get for
31 # more information.
32 def thread_variable_set(key, value)
33 locals[key.to_sym] = value
34 end
35
36 # Returns an an array of the names of the thread-local variables (as Symbols).
37 #
38 # thr = Thread.new do
39 # Thread.current.thread_variable_set(:cat, 'meow')
40 # Thread.current.thread_variable_set("dog", 'woof')
41 # end
42 # thr.join #=> #<Thread:0x401b3f10 dead>
43 # thr.thread_variables #=> [:dog, :cat]
44 #
45 # Note that these are not fiber local variables. Please see Thread#thread_variable_get
46 # for more details.
47 def thread_variables
48 locals.keys
49 end
50
51 # Returns <tt>true</tt> if the given string (or symbol) exists as a
52 # thread-local variable.
53 #
54 # me = Thread.current
55 # me.thread_variable_set(:oliver, "a")
56 # me.thread_variable?(:oliver) #=> true
57 # me.thread_variable?(:stanley) #=> false
58 #
59 # Note that these are not fiber local variables. Please see Thread#thread_variable_get
60 # for more details.
61 def thread_variable?(key)
62 locals.has_key?(key.to_sym)
63 end
64
65 private
66
67 def locals
7f7c09c @rafaelfranca Remove warning of intance variable not initialized
rafaelfranca authored
68 if defined?(@locals)
69 @locals
70 else
71 LOCK.synchronize { @locals ||= {} }
72 end
a565f80 @rafaelfranca Backport thread-local variables from Ruby 2.0
rafaelfranca authored
73 end
74 end unless Thread.instance_methods.include?(:thread_variable_set)
Something went wrong with that request. Please try again.