Documentation ¶
Overview ¶
Package sync provides advanced synchronization tools.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type MutexMap ¶
type MutexMap struct {
// contains filtered or unexported fields
}
MutexMap allows to obtain a mutex lock that is scoped to a given string key. I.e. only one goroutine at a time can hold the lock for the same key, while locks for different keys are independent.
An example use case might be a HTTP service that processes requests concurrently, but we want to make sure that at most one request for the same user is handled at a time. To achieve this, one can share a single MutexMap across all http handler goroutines and the http handler obtains the lock for the user (by e.g. using a userId as the key for the MutexMap) before doing any work.
Example usage:
mm := NewMutexMap() l := mm.Lock("exampleKey") // prefer to call Unlock() with defer right after locking, to make sure the lock gets unlocked eventually defer l.Unlock()
Careful: nested locks, i.e. trying to obtain a lock for key x while already holding the lock for key y, can lead to deadlocks.
Implementation slightly adapted from answer https://stackoverflow.com/a/62562831 to https://stackoverflow.com/questions/40931373/how-to-gc-a-map-of-mutexes-in-go .
func NewMutexMap ¶
func NewMutexMap() *MutexMap