ctxlock

package
v0.31.0 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2023 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrQueueFull is returned when the queue is full and a lock is requested.
	ErrQueueFull = errors.New("queue full")

	// ErrTimeout is returned when the lock request times out while waiting in
	// the queue.
	ErrTimeout = errors.New("timeout")
)

Functions

This section is empty.

Types

type Config

type Config struct {
	// MaxHeld indicates the maximum number of locks that can be held at once,
	// per ID.
	//
	// If MaxHeld is not set, it defaults to 1.
	MaxHeld int

	// MaxWait indicates the maximum number of pending locks that can be
	// queued for a given ID.
	//
	// If MaxWait is -1, no limit is enforced.
	MaxWait int

	// Timeout indicates the maximum amount of time to wait for a lock to be
	// acquired.
	//
	// If Timeout is 0, no timeout is enforced.
	Timeout time.Duration
}

Config is the configuration for an IDLocker.

type IDLocker

type IDLocker[K comparable] struct {
	// contains filtered or unexported fields
}

IDLocker allows multiple locks to be held at once, but only up to a certain number of locks per ID.

If the number of locks for an ID exceeds the maximum, the lock will be queued until a lock is released.

It is safe to use IDLocker from multiple goroutines and is used to manage concurrency.

func NewIDLocker

func NewIDLocker[K comparable](cfg Config) *IDLocker[K]

NewIDLocker creates a new IDLocker with the given config.

An empty config will result in a locker that allows only one lock to be held at a time, with no queue (i.e., ErrQueueFull will be returned if a lock is requested while another is held).

func (*IDLocker[K]) Lock

func (l *IDLocker[K]) Lock(ctx context.Context, id K) error

Lock will attempt to acquire a lock for the given ID.

If Lock returns nil, Unlock must be called to release the lock, even if the context is canceled.

func (*IDLocker[K]) Unlock

func (l *IDLocker[K]) Unlock(id K)
Unlock will release a lock for the given ID.

If there are any pending locks, the next one will be granted.

Note: Unlock will panic if called more times than Lock.

Jump to

Keyboard shortcuts

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