A thread-safe Hash that delegates all its methods to a real hash
#!/usr/local/bin/ruby -w
#!/usr/local/ruby -w
require 'rubygems'
require 'facet/basicobject' # for the BasicObject class
require 'thread' # for the Mutex class
# A thread-safe Hash that delegates all its methods to a real hash
class ThreadsafeHash < BasicObject
def initialize (*args, &block)
@hash = Hash.new(*args, &block) # The shared hash
@lock = Mutex.new # For thread safety
end
def method_missing(method, *args, &block)
if @hash.respond_to? method # Forward Hash method calls...
@lock.synchronize do # but wrap them in a thread safe lock
@hash.send(method, *args, &block)
end
else
super
end
end
end