counter.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package graphdriver
  2. import "sync"
  3. type minfo struct {
  4. check bool
  5. count int
  6. }
  7. // RefCounter is a generic counter for use by graphdriver Get/Put calls
  8. type RefCounter struct {
  9. counts map[string]*minfo
  10. mu sync.Mutex
  11. checker Checker
  12. }
  13. // NewRefCounter returns a new RefCounter
  14. func NewRefCounter(c Checker) *RefCounter {
  15. return &RefCounter{
  16. checker: c,
  17. counts: make(map[string]*minfo),
  18. }
  19. }
  20. // Increment increaes the ref count for the given id and returns the current count
  21. func (c *RefCounter) Increment(path string) int {
  22. c.mu.Lock()
  23. m := c.counts[path]
  24. if m == nil {
  25. m = &minfo{}
  26. c.counts[path] = m
  27. }
  28. // if we are checking this path for the first time check to make sure
  29. // if it was already mounted on the system and make sure we have a correct ref
  30. // count if it is mounted as it is in use.
  31. if !m.check {
  32. m.check = true
  33. if c.checker.IsMounted(path) {
  34. m.count++
  35. }
  36. }
  37. m.count++
  38. c.mu.Unlock()
  39. return m.count
  40. }
  41. // Decrement decreases the ref count for the given id and returns the current count
  42. func (c *RefCounter) Decrement(path string) int {
  43. c.mu.Lock()
  44. m := c.counts[path]
  45. if m == nil {
  46. m = &minfo{}
  47. c.counts[path] = m
  48. }
  49. // if we are checking this path for the first time check to make sure
  50. // if it was already mounted on the system and make sure we have a correct ref
  51. // count if it is mounted as it is in use.
  52. if !m.check {
  53. m.check = true
  54. if c.checker.IsMounted(path) {
  55. m.count++
  56. }
  57. }
  58. m.count--
  59. c.mu.Unlock()
  60. return m.count
  61. }