github.com/hashicorp/terraform-plugin-sdk@v1.17.2/helper/mutexkv/mutexkv.go (about) 1 package mutexkv 2 3 import ( 4 "log" 5 "sync" 6 ) 7 8 // MutexKV is a simple key/value store for arbitrary mutexes. It can be used to 9 // serialize changes across arbitrary collaborators that share knowledge of the 10 // keys they must serialize on. 11 // 12 // Deprecated: This will be removed in v2 without replacement. If you need 13 // its functionality, you can copy it or reference the v1 package. 14 // 15 // The initial use case is to let aws_security_group_rule resources serialize 16 // their access to individual security groups based on SG ID. 17 type MutexKV struct { 18 lock sync.Mutex 19 store map[string]*sync.Mutex 20 } 21 22 // Locks the mutex for the given key. Caller is responsible for calling Unlock 23 // for the same key 24 // 25 // Deprecated: This will be removed in v2 without replacement. If you need 26 // its functionality, you can copy it or reference the v1 package. 27 func (m *MutexKV) Lock(key string) { 28 log.Printf("[DEBUG] Locking %q", key) 29 m.get(key).Lock() 30 log.Printf("[DEBUG] Locked %q", key) 31 } 32 33 // Unlock the mutex for the given key. Caller must have called Lock for the same key first 34 // 35 // Deprecated: This will be removed in v2 without replacement. If you need 36 // its functionality, you can copy it or reference the v1 package. 37 func (m *MutexKV) Unlock(key string) { 38 log.Printf("[DEBUG] Unlocking %q", key) 39 m.get(key).Unlock() 40 log.Printf("[DEBUG] Unlocked %q", key) 41 } 42 43 // Returns a mutex for the given key, no guarantee of its lock status 44 func (m *MutexKV) get(key string) *sync.Mutex { 45 m.lock.Lock() 46 defer m.lock.Unlock() 47 mutex, ok := m.store[key] 48 if !ok { 49 mutex = &sync.Mutex{} 50 m.store[key] = mutex 51 } 52 return mutex 53 } 54 55 // Returns a properly initalized MutexKV 56 // 57 // Deprecated: This will be removed in v2 without replacement. If you need 58 // its functionality, you can copy it or reference the v1 package. 59 func NewMutexKV() *MutexKV { 60 return &MutexKV{ 61 store: make(map[string]*sync.Mutex), 62 } 63 }