Guest User

Untitled

a guest
Jun 24th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. # I need only 1 hash in the entire application
  2. # Only 1 thread will ever write data into the hash
  3. # 100s of threads will perform read()s and delete()s
  4. # Here's my first pass at a thread safe hash, not generalized, but for this one app
  5. # 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
  6.  
  7. class MyThreadSafeHash
  8. @@hash = {}
  9. @@mutex = Mutex.new
  10.  
  11. def self.write(key, value)
  12. @@mutex.synchronize do
  13. @@hash[key] = value
  14. end
  15. end
  16.  
  17. # Is synchronize needed for read?
  18. def self.read(key)
  19. value = nil
  20. @@mutex.synchronize do
  21. value = @@hash[key]
  22. end
  23. value
  24. end
  25.  
  26. def self.delete(key)
  27. @@mutex.synchronize do
  28. @@hash.delete(key)
  29. end
  30. end
  31.  
  32. def self.snatch(key)
  33. value = nil
  34. while (true)
  35. value = self.read(key)
  36. break if value
  37. sleep 0.010
  38. end
  39. value
  40. end
  41. end
Add Comment
Please, Sign In to add comment