| 1 |
/* |
| 2 |
Copyright The containerd Authors. |
| 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 namedmutex provides NamedMutex that wraps sync.Mutex |
| 18 |
// and provides namespaced mutex. |
| 19 |
package namedmutex |
| 20 |
|
| 21 |
import ( |
| 22 |
"sync" |
| 23 |
) |
| 24 |
|
| 25 |
// NamedMutex wraps sync.Mutex and provides namespaced mutex. |
| 26 |
type NamedMutex struct { |
| 27 |
muMap map[string]*sync.Mutex |
| 28 |
refMap map[string]int |
| 29 |
|
| 30 |
mu sync.Mutex |
| 31 |
} |
| 32 |
|
| 33 |
// Lock locks the mutex of the given name |
| 34 |
func (nl *NamedMutex) Lock(name string) { |
| 35 |
nl.mu.Lock() |
| 36 |
if nl.muMap == nil { |
| 37 |
nl.muMap = make(map[string]*sync.Mutex) |
| 38 |
} |
| 39 |
if nl.refMap == nil { |
| 40 |
nl.refMap = make(map[string]int) |
| 41 |
} |
| 42 |
if _, ok := nl.muMap[name]; !ok { |
| 43 |
nl.muMap[name] = &sync.Mutex{} |
| 44 |
} |
| 45 |
mu := nl.muMap[name] |
| 46 |
nl.refMap[name]++ |
| 47 |
nl.mu.Unlock() |
| 48 |
mu.Lock() |
| 49 |
} |
| 50 |
|
| 51 |
// Unlock unlocks the mutex of the given name |
| 52 |
func (nl *NamedMutex) Unlock(name string) { |
| 53 |
nl.mu.Lock() |
| 54 |
mu := nl.muMap[name] |
| 55 |
nl.refMap[name]-- |
| 56 |
if nl.refMap[name] <= 0 { |
| 57 |
delete(nl.muMap, name) |
| 58 |
delete(nl.refMap, name) |
| 59 |
} |
| 60 |
nl.mu.Unlock() |
| 61 |
mu.Unlock() |
| 62 |
} |