locks.go 346 B

123456789101112131415161718192021222324252627
  1. package gold
  2. import (
  3. "sync"
  4. )
  5. var (
  6. locksL = new(sync.Mutex)
  7. locks = map[string]*sync.Mutex{}
  8. )
  9. func lock(key string) func() {
  10. mu, ex := locks[key]
  11. if !ex { // TTAS
  12. locksL.Lock()
  13. mu, ex = locks[key]
  14. if !ex {
  15. locks[key] = new(sync.Mutex)
  16. }
  17. locksL.Unlock()
  18. mu = locks[key]
  19. }
  20. mu.Lock()
  21. return func() {
  22. mu.Unlock()
  23. }
  24. }