github.com/sacloud/libsacloud/v2@v2.32.3/pkg/mutexkv/mutexkv.go (about)

     1  // Copyright 2016-2022 The Libsacloud Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package mutexkv
    16  
    17  import (
    18  	"sync"
    19  )
    20  
    21  // MutexKV is a simple key/value store for arbitrary mutexes. It can be used to
    22  // serialize changes across arbitrary collaborators that share knowledge of the
    23  // keys they must serialize on.
    24  type MutexKV struct {
    25  	lock  sync.Mutex
    26  	store map[string]*sync.Mutex
    27  }
    28  
    29  // Lock the mutex for the given key. Caller is responsible for calling Unlock
    30  // for the same key
    31  func (m *MutexKV) Lock(key string) {
    32  	m.get(key).Lock()
    33  }
    34  
    35  // Unlock the mutex for the given key. Caller must have called Lock for the same key first
    36  func (m *MutexKV) Unlock(key string) {
    37  	m.get(key).Unlock()
    38  }
    39  
    40  // Returns a mutex for the given key, no guarantee of its lock status
    41  func (m *MutexKV) get(key string) *sync.Mutex {
    42  	m.lock.Lock()
    43  	defer m.lock.Unlock()
    44  	mutex, ok := m.store[key]
    45  	if !ok {
    46  		mutex = &sync.Mutex{}
    47  		m.store[key] = mutex
    48  	}
    49  	return mutex
    50  }
    51  
    52  // NewMutexKV Returns a properly initialized MutexKV
    53  func NewMutexKV() *MutexKV {
    54  	return &MutexKV{
    55  		store: make(map[string]*sync.Mutex),
    56  	}
    57  }