| 1 |
/* |
| 2 |
Copyright 2018 The Kubernetes 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 keymutex |
| 18 |
|
| 19 |
import ( |
| 20 |
"hash/fnv" |
| 21 |
"runtime" |
| 22 |
"sync" |
| 23 |
) |
| 24 |
|
| 25 |
// NewHashed returns a new instance of KeyMutex which hashes arbitrary keys to |
| 26 |
// a fixed set of locks. `n` specifies number of locks, if n <= 0, we use |
| 27 |
// number of cpus. |
| 28 |
// Note that because it uses fixed set of locks, different keys may share same |
| 29 |
// lock, so it's possible to wait on same lock. |
| 30 |
func NewHashed(n int) KeyMutex { |
| 31 |
if n <= 0 { |
| 32 |
n = runtime.NumCPU() |
| 33 |
} |
| 34 |
return &hashedKeyMutex{ |
| 35 |
mutexes: make([]sync.Mutex, n), |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
type hashedKeyMutex struct { |
| 40 |
mutexes []sync.Mutex |
| 41 |
} |
| 42 |
|
| 43 |
// Acquires a lock associated with the specified ID. |
| 44 |
func (km *hashedKeyMutex) LockKey(id string) { |
| 45 |
km.mutexes[km.hash(id)%uint32(len(km.mutexes))].Lock() |
| 46 |
} |
| 47 |
|
| 48 |
// Releases the lock associated with the specified ID. |
| 49 |
func (km *hashedKeyMutex) UnlockKey(id string) error { |
| 50 |
km.mutexes[km.hash(id)%uint32(len(km.mutexes))].Unlock() |
| 51 |
return nil |
| 52 |
} |
| 53 |
|
| 54 |
func (km *hashedKeyMutex) hash(id string) uint32 { |
| 55 |
h := fnv.New32a() |
| 56 |
h.Write([]byte(id)) |
| 57 |
return h.Sum32() |
| 58 |
} |