The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Thread local variables

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Florian Frank

Posts: 48
Nickname: ffrank
Registered: Dec, 2005

Florian Frank is a humanoid life-form, living on the third planet of the solar system.
Thread local variables Posted: May 2, 2006 8:08 AM
Reply to this message Reply

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           # => 1
Thread.new do
  mc.test == nil  # => true
  mc.test = 2
end
mc.test           # => 1

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

Topic: MASC Textmate Bundle Previous Topic   Next Topic Topic: Workflow / BPEL Engines en Java

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use