hashed.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package keymutex
  14. import (
  15. "hash/fnv"
  16. "runtime"
  17. "sync"
  18. )
  19. // NewHashed returns a new instance of KeyMutex which hashes arbitrary keys to
  20. // a fixed set of locks. `n` specifies number of locks, if n <= 0, we use
  21. // number of cpus.
  22. // Note that because it uses fixed set of locks, different keys may share same
  23. // lock, so it's possible to wait on same lock.
  24. func NewHashed(n int) KeyMutex {
  25. if n <= 0 {
  26. n = runtime.NumCPU()
  27. }
  28. return &hashedKeyMutex{
  29. mutexes: make([]sync.Mutex, n),
  30. }
  31. }
  32. type hashedKeyMutex struct {
  33. mutexes []sync.Mutex
  34. }
  35. // Acquires a lock associated with the specified ID.
  36. func (km *hashedKeyMutex) LockKey(id string) {
  37. km.mutexes[km.hash(id)%uint32(len(km.mutexes))].Lock()
  38. }
  39. // Releases the lock associated with the specified ID.
  40. func (km *hashedKeyMutex) UnlockKey(id string) error {
  41. km.mutexes[km.hash(id)%uint32(len(km.mutexes))].Unlock()
  42. return nil
  43. }
  44. func (km *hashedKeyMutex) hash(id string) uint32 {
  45. h := fnv.New32a()
  46. h.Write([]byte(id))
  47. return h.Sum32()
  48. }