Thread Safe Global Variables in Ruby

Let's say you have a standard Ruby application, where you decided to use some global variables to ease the access to some standard information that you need across all your code, without resorting to send the global object as a parameter everywhere. ```ruby

    $global_var = SomeClass.new

```

Now let's pretend that out of nowhere you decided that you need multiple threads to run your application. Usually you would code something like this to start each thread: ```ruby

2.times do
    Thread.new {
        $global_var = SomeClass.new
        #execute some more code...
    }
end

```

As your application worked before, you would expect each thread to have its own $global_var but no, global variables are shared among all threads, so suddenly your reports show mixed steps, wrong values in calculations, and everything stops behaving like you would expect it.

This behavior is by design. Global variables are suppossed to be accesible from every single place of your code, so naturally, even though threads are independent, the global variables are not.

So, what can be done to have something between a global variable (to avoid passing it around by value across all your methods), and a local variable (so each thread can have its own and not peek or write outside itself)?

Well, turns out that the Thread ruby class has an instance method to set and get thread-local variables as if the Thread instance was a Hash, and it works just as expected.

First of all you need to reference the running thread. This can be done with the 'current' class method: ```ruby

5.times do
    Thread.new {
        Thread.current
        #$global_var = SomeClass.new -- we will not need this anymore
        #execute some more code...
    }
end

```

And then, you treat the current thread as a hash of key-value pairs: ```ruby

5.times do
    Thread.new {
        Thread.current['local_var'] = SomeClass.new
        #$global_var = SomeClass.new -- we will not need this anymore
        #execute some more code...
    }
end

```

And that's it, you can access the value from anywhere within the thread by ```ruby

Thread.current['local_var']

```