Skip to content

Instantly share code, notes, and snippets.

@alexec
Created December 29, 2022 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexec/771aa9abeb293f9e2e1381f5ce1f47e8 to your computer and use it in GitHub Desktop.
Save alexec/771aa9abeb293f9e2e1381f5ce1f47e8 to your computer and use it in GitHub Desktop.
package proc
import "sync"
var locks = &sync.Map{}
// KeyLock return a mutex for the key.
// This func never frees un-locked mutexes. It is only suitable for use-cases with a small number of keys.
func KeyLock(key string) *sync.Mutex {
actual, _ := locks.LoadOrStore(key, &sync.Mutex{})
mutex := actual.(*sync.Mutex)
return mutex
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment