github.com/timstclair/heapster@v0.20.0-alpha1/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/keymutex/keymutex.go (about) 1 /* 2 Copyright 2015 The Kubernetes Authors All rights reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package keymutex 18 19 import ( 20 "fmt" 21 "github.com/golang/glog" 22 "sync" 23 ) 24 25 // KeyMutex is a thread-safe interface for aquiring locks on arbitrary strings. 26 type KeyMutex interface { 27 // Aquires a lock associated with the specified ID, creates the lock if one doesn't already exist. 28 LockKey(id string) 29 30 // Releases the lock associated with the specified ID. 31 // Returns an error if the specified ID doesn't exist. 32 UnlockKey(id string) error 33 } 34 35 // Returns a new instance of a key mutex. 36 func NewKeyMutex() KeyMutex { 37 return &keyMutex{ 38 mutexMap: make(map[string]*sync.Mutex), 39 } 40 } 41 42 type keyMutex struct { 43 sync.RWMutex 44 mutexMap map[string]*sync.Mutex 45 } 46 47 // Aquires a lock associated with the specified ID (creates the lock if one doesn't already exist). 48 func (km *keyMutex) LockKey(id string) { 49 glog.V(5).Infof("LockKey(...) called for id %q\r\n", id) 50 mutex := km.getOrCreateLock(id) 51 mutex.Lock() 52 glog.V(5).Infof("LockKey(...) for id %q completed.\r\n", id) 53 } 54 55 // Releases the lock associated with the specified ID. 56 // Returns an error if the specified ID doesn't exist. 57 func (km *keyMutex) UnlockKey(id string) error { 58 glog.V(5).Infof("UnlockKey(...) called for id %q\r\n", id) 59 km.RLock() 60 defer km.RUnlock() 61 mutex, exists := km.mutexMap[id] 62 if !exists { 63 return fmt.Errorf("id %q not found", id) 64 } 65 glog.V(5).Infof("UnlockKey(...) for id. Mutex found, trying to unlock it. %q\r\n", id) 66 67 mutex.Unlock() 68 glog.V(5).Infof("UnlockKey(...) for id %q completed.\r\n", id) 69 return nil 70 } 71 72 // Returns lock associated with the specified ID, or creates the lock if one doesn't already exist. 73 func (km *keyMutex) getOrCreateLock(id string) *sync.Mutex { 74 km.Lock() 75 defer km.Unlock() 76 77 if _, exists := km.mutexMap[id]; !exists { 78 km.mutexMap[id] = &sync.Mutex{} 79 } 80 81 return km.mutexMap[id] 82 }