counter.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. count := m.count
  39. c.mu.Unlock()
  40. return count
  41. }
  42. // Decrement decreases the ref count for the given id and returns the current count
  43. func (c *RefCounter) Decrement(path string) int {
  44. c.mu.Lock()
  45. m := c.counts[path]
  46. if m == nil {
  47. m = &minfo{}
  48. c.counts[path] = m
  49. }
  50. // if we are checking this path for the first time check to make sure
  51. // if it was already mounted on the system and make sure we have a correct ref
  52. // count if it is mounted as it is in use.
  53. if !m.check {
  54. m.check = true
  55. if c.checker.IsMounted(path) {
  56. m.count++
  57. }
  58. }
  59. m.count--
  60. count := m.count
  61. c.mu.Unlock()
  62. return count
  63. }