single_instance_pool.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2016 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package sync
  5. import (
  6. "sync"
  7. )
  8. // SingleInstancePool is a pool of non-identical instances
  9. // that only one instance with same identity is in the pool at a time.
  10. // In other words, only instances with different identities can exist
  11. // at the same time.
  12. //
  13. // This pool is particularly useful for performing tasks on same resource
  14. // on the file system in different goroutines.
  15. type SingleInstancePool struct {
  16. lock sync.Mutex
  17. // pool maintains locks for each instance in the pool.
  18. pool map[string]*sync.Mutex
  19. // count maintains the number of times an instance with same identity checks in
  20. // to the pool, and should be reduced to 0 (removed from map) by checking out
  21. // with same number of times.
  22. count map[string]int
  23. }
  24. // NewSingleInstancePool initializes and returns a new SingleInstancePool object.
  25. func NewSingleInstancePool() *SingleInstancePool {
  26. return &SingleInstancePool{
  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 *SingleInstancePool) 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 *SingleInstancePool) 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. }