You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

exclusive_pool.go 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2016 The Gogs Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package sync
  4. import (
  5. "sync"
  6. )
  7. // ExclusivePool is a pool of non-identical instances
  8. // that only one instance with same identity is in the pool at a time.
  9. // In other words, only instances with different identities can be in
  10. // the pool the same time. If another instance with same identity tries
  11. // to get into the pool, it hangs until previous instance left the pool.
  12. //
  13. // This pool is particularly useful for performing tasks on same resource
  14. // on the file system in different goroutines.
  15. type ExclusivePool 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. // The purpose of count is to delete lock when count down to 0 and recycle memory
  23. // from map object.
  24. count map[string]int
  25. }
  26. // NewExclusivePool initializes and returns a new ExclusivePool object.
  27. func NewExclusivePool() *ExclusivePool {
  28. return &ExclusivePool{
  29. pool: make(map[string]*sync.Mutex),
  30. count: make(map[string]int),
  31. }
  32. }
  33. // CheckIn checks in an instance to the pool and hangs while instance
  34. // with same identity is using the lock.
  35. func (p *ExclusivePool) CheckIn(identity string) {
  36. p.lock.Lock()
  37. lock, has := p.pool[identity]
  38. if !has {
  39. lock = &sync.Mutex{}
  40. p.pool[identity] = lock
  41. }
  42. p.count[identity]++
  43. p.lock.Unlock()
  44. lock.Lock()
  45. }
  46. // CheckOut checks out an instance from the pool and releases the lock
  47. // to let other instances with same identity to grab the lock.
  48. func (p *ExclusivePool) CheckOut(identity string) {
  49. p.lock.Lock()
  50. defer p.lock.Unlock()
  51. p.pool[identity].Unlock()
  52. if p.count[identity] == 1 {
  53. delete(p.pool, identity)
  54. delete(p.count, identity)
  55. } else {
  56. p.count[identity]--
  57. }
  58. }