The code you are referencing is not thread safe. It uses the ruby Hash class, which is not thread safe. You can protect access using one of the ruby synchronization primitives, for example. Mutex.
Also, I'm not sure that using a global data structure indexed by a thread id is no better than just using Thread.current.
If you are worried about a key collision, why not choose a unique key, such as a GUID. Based on the example in the link provided:
class ThreadedLibrary
@@LIBRARY_ID = 'D0052660-60E6-4624-B08E-ECA9200B2949'
Thread.current[@@LIBRARY_ID] = {}
def self.some_setting= val
Thread.current[@@LIBRARY_ID][:some_setting] = val
end
def self.some_setting
Thread.current[@@LIBRARY_ID][:some_setting] ||= :default
end
end
source
share