Posts Tagged ‘concurrency’

Thread local variables in ruby

The following is taken from the Pickaxe

As we described in the previous section, a thread can normally access any variables that are in scope when the thread is created. Variables local to the block of a thread are local to the thread, and are not shared.But what if you need per-thread variables that can be accessed by other threads — including the main thread? Thread features a special facility that allows thread-local variables to be created and accessed by name. You simply treat the thread object as if it were a Hash, writing to elements using []= and reading them back using [].

Thread.current[:thread_local_var] = :foo
Thread.current[:thread_local_var] # prints foo