github.com/mgoltzsche/ctnr@v0.7.1-alpha/pkg/lock/mutex.go (about) 1 package lock 2 3 import ( 4 "sync" 5 ) 6 7 var ( 8 locks = map[string]*kvmutex{} 9 mutex = &sync.Mutex{} 10 ) 11 12 type kvmutex struct { 13 mutex sync.Mutex 14 count uint 15 } 16 17 func lock(key string) { 18 l := mutexRef(key) 19 l.mutex.Lock() 20 } 21 22 func mutexRef(key string) *kvmutex { 23 mutex.Lock() 24 defer mutex.Unlock() 25 26 l := locks[key] 27 if l == nil { 28 l = &kvmutex{} 29 locks[key] = l 30 } 31 l.count++ 32 return l 33 } 34 35 func unlock(key string) { 36 mutex.Lock() 37 defer mutex.Unlock() 38 39 l := locks[key] 40 if l == nil { 41 panic("unlock: mutex unlocked: " + key) 42 } 43 l.mutex.Unlock() 44 l.count-- 45 if l.count == 0 { 46 delete(locks, key) 47 } 48 }