本站源代码
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

71 lines
2.0KB

  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. // ExclusivePool 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 be in
  11. // the pool the same time. If another instance with same identity tries
  12. // to get into the pool, it hangs until previous instance left the pool.
  13. //
  14. // This pool is particularly useful for performing tasks on same resource
  15. // on the file system in different goroutines.
  16. type ExclusivePool struct {
  17. lock sync.Mutex
  18. // pool maintains locks for each instance in the pool.
  19. pool map[string]*sync.Mutex
  20. // count maintains the number of times an instance with same identity checks in
  21. // to the pool, and should be reduced to 0 (removed from map) by checking out
  22. // with same number of times.
  23. // The purpose of count is to delete lock when count down to 0 and recycle memory
  24. // from map object.
  25. count map[string]int
  26. }
  27. // NewExclusivePool initializes and returns a new ExclusivePool object.
  28. func NewExclusivePool() *ExclusivePool {
  29. return &ExclusivePool{
  30. pool: make(map[string]*sync.Mutex),
  31. count: make(map[string]int),
  32. }
  33. }
  34. // CheckIn checks in an instance to the pool and hangs while instance
  35. // with same identity is using the lock.
  36. func (p *ExclusivePool) CheckIn(identity string) {
  37. p.lock.Lock()
  38. lock, has := p.pool[identity]
  39. if !has {
  40. lock = &sync.Mutex{}
  41. p.pool[identity] = lock
  42. }
  43. p.count[identity]++
  44. p.lock.Unlock()
  45. lock.Lock()
  46. }
  47. // CheckOut checks out an instance from the pool and releases the lock
  48. // to let other instances with same identity to grab the lock.
  49. func (p *ExclusivePool) CheckOut(identity string) {
  50. p.lock.Lock()
  51. defer p.lock.Unlock()
  52. p.pool[identity].Unlock()
  53. if p.count[identity] == 1 {
  54. delete(p.pool, identity)
  55. delete(p.count, identity)
  56. } else {
  57. p.count[identity]--
  58. }
  59. }
上海开阖软件有限公司 沪ICP备12045867号-1