sync

package
v0.4.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 22, 2024 License: MIT Imports: 1 Imported by: 0

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

func (*MutexMap) Lock

func (mm *MutexMap) Lock(key string) Unlocker

Obtain the lock for the given key. If the lock is already held by another goroutine, this function blocks until the lock is released. The calling goroutine can use the returned Unlocker to unlock the given key when done.

type Unlocker

type Unlocker interface {
	Unlock()
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL