This post originated from an RSS feed registered with Ruby Buzz
by Florian Frank.
Original Post: Thread local variables
Feed Title: The Rubylution: Tag Ruby
Feed URL: http://rubylution.ping.de/xml/rss/tag/ruby/feed.xml
Feed Description: Starts… Now.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Florian Frank
Latest Posts From The Rubylution: Tag Ruby
Advertisement
Here's a small module extension, that makes a thread_local method available, to define a thread local attribute in a class.
module ThreadLocalExtension
def thread_local ( name )
klass , name = self . to_s , name . to_s
define_method ( name ) do
Thread . current [" __#{klass} _#{name} __ ". intern ]
end
define_method ( name + " = ") do | value |
Thread . current [" __#{klass} _#{name} __ ". intern ] = value
end
end
end
And here's the proof, that it works:
class MyClass
extend ThreadLocalExtension
thread_local :test
end
mc = MyClass . new
mc . test = 1
mc . test
Thread . new do
mc . test == nil
mc . test = 2
end
mc . test
I never stop being amazed, what you can do in just a few lines of Ruby - and it's neat, too.
Read: Thread local variables