exclusive_pool.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package sync
  2. import (
  3. "sync"
  4. )
  5. // ExclusivePool is a pool of non-identical instances
  6. // that only one instance with same identity is in the pool at a time.
  7. // In other words, only instances with different identities can be in
  8. // the pool the same time. If another instance with same identity tries
  9. // to get into the pool, it hangs until previous instance left the pool.
  10. //
  11. // This pool is particularly useful for performing tasks on same resource
  12. // on the file system in different goroutines.
  13. type ExclusivePool struct {
  14. lock sync.Mutex
  15. // pool maintains locks for each instance in the pool.
  16. pool map[string]*sync.Mutex
  17. // count maintains the number of times an instance with same identity checks in
  18. // to the pool, and should be reduced to 0 (removed from map) by checking out
  19. // with same number of times.
  20. // The purpose of count is to delete lock when count down to 0 and recycle memory
  21. // from map object.
  22. count map[string]int
  23. }
  24. // NewExclusivePool initializes and returns a new ExclusivePool object.
  25. func NewExclusivePool() *ExclusivePool {
  26. return &ExclusivePool{
  27. pool: make(map[string]*sync.Mutex),
  28. count: make(map[string]int),
  29. }
  30. }
  31. // CheckIn checks in an instance to the pool and hangs while instance
  32. // with same indentity is using the lock.
  33. func (p *ExclusivePool) CheckIn(identity string) {
  34. p.lock.Lock()
  35. lock, has := p.pool[identity]
  36. if !has {
  37. lock = &sync.Mutex{}
  38. p.pool[identity] = lock
  39. }
  40. p.count[identity]++
  41. p.lock.Unlock()
  42. lock.Lock()
  43. }
  44. // CheckOut checks out an instance from the pool and releases the lock
  45. // to let other instances with same identity to grab the lock.
  46. func (p *ExclusivePool) CheckOut(identity string) {
  47. p.lock.Lock()
  48. defer p.lock.Unlock()
  49. p.pool[identity].Unlock()
  50. if p.count[identity] == 1 {
  51. delete(p.pool, identity)
  52. delete(p.count, identity)
  53. } else {
  54. p.count[identity]--
  55. }
  56. }