Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # I need only 1 hash in the entire application
- # Only 1 thread will ever write data into the hash
- # 100s of threads will perform read()s and delete()s
- # Here's my first pass at a thread safe hash, not generalized, but for this one app
- # The threads never talk to each other, not even to the one that writes, so I'm using class methods rather than finding a way to pass around the reference to an instance
- class MyThreadSafeHash
- @@hash = {}
- @@mutex = Mutex.new
- def self.write(key, value)
- @@mutex.synchronize do
- @@hash[key] = value
- end
- end
- # Is synchronize needed for read?
- def self.read(key)
- value = nil
- @@mutex.synchronize do
- value = @@hash[key]
- end
- value
- end
- def self.delete(key)
- @@mutex.synchronize do
- @@hash.delete(key)
- end
- end
- def self.snatch(key)
- value = nil
- while (true)
- value = self.read(key)
- break if value
- sleep 0.010
- end
- value
- end
- end
Add Comment
Please, Sign In to add comment