hashlock

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2021 License: MIT Imports: 3 Imported by: 0

README

hashlock

codecov Go Reference

Description

Package hashlock provides a way to lock multiple string indexes and only allow write access to a resource to one thread at a time

Battle-tested in multi-threaded applications with thousands concurrent writes and reads per minute

Background

Most lock mechanisms in golang use sync.Mutex which works quite well most of the time.

However, if someone tries to acquire an uninitialized Mutex, a non-recoverable error will occur. Checking if the Mutex is initialized may require complex custom logic

That is the reason this library uses boolean channels to handle locking which handle pretty well in terms of stability and performance

IMPORTANT NOTE

This library is not designed to be a queue, so do not expect a FIFO or any other behavior

The goal is to avoid multiple threads writing to the same resource, while keeping it available for concurrent reads

Usage

import "github.com/montexristos/hashlock"

hashLock := (&HashLock{}).New(1 * time.Second)

// lock the value for read/write
hashLock.Lock("awesomeKey")
defer hashLock.Unlock("awesomeKey")

//
go hashLock.Lock("awesomeKey")

// the goroutine initiated above will wait for the current function to release the lock

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type HashLock

type HashLock struct {
	// contains filtered or unexported fields
}

HashLock keeps a hashmap with unique keys and lock conditions Also has a rw mutex for the hashmap to avoid race conditions between threads If timeout is set the lock is unlocked after the given time

func (*HashLock) DeleteKey

func (l *HashLock) DeleteKey(key string)

DeleteKey removes a key from hashmap with locks

func (*HashLock) Empty

func (l *HashLock) Empty(force bool) bool

Empty removes all non used keys from hashmap to release memory

func (*HashLock) GetLockKey

func (l *HashLock) GetLockKey(args []string) string

GetLockKey provides a pattern for creating keys from string arrays

func (*HashLock) Lock

func (l *HashLock) Lock(key string)

Lock locks the provided key for rw

func (*HashLock) New

func (l *HashLock) New(d time.Duration) *HashLock

New initializes a new HashLock

func (*HashLock) Unlock

func (l *HashLock) Unlock(key string)

Unlock unlocks the provided key for rw

Jump to

Keyboard shortcuts

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