stripedmutex

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2019 License: MIT Imports: 3 Imported by: 1

README

Build Status codecov

Striped-Mutex

Implementation of a Striped-Mutex inspired from Guava Java lib Guava: https://github.com/google/guava/wiki/StripedExplained

Striped-Mutex allows to fined grained locking of multiple distinct objects by basing on a indexation key.

package main

import (
    stripedmutex "github.com/nmvalera/striped-mutex"
)

func main() {
    // Create a striped mutex with 20 locks
    smux := stripedmutex.New(20)

    smux.Lock("key")
    defer smux.Lock("key")

    // ... do something in a concurrent manner in scope associated to "key"
}

Implementation

A straightforward implementation would be to create a lock for every key. While this approach leads to minimal lock contention, it results in a linear memory usage wrt the count of keys which can be unsastifying when dealing with a large number of keys.

Striped-Mutex allows to configure a number of locks that are distributed between keys based on their hash code. It allows to select a tradeoff between concurrency and memory consumption, while retaining the property that if key1 == key2 then lock associated to key1 and key2 is the same.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type StripedMutex

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

StripedMutex is an object that allows fine grained locking based on keys

It ensures that if `key1 == key2` then lock associated with `key1` is the same as the one associated with `key2` It holds a stable number of locks in memory that use can control

It is inspired from Java lib Guava: https://github.com/google/guava/wiki/StripedExplained

func New

func New(stripes uint) *StripedMutex

New creates a StripedMutex

func (*StripedMutex) GetLock

func (m *StripedMutex) GetLock(key string) (*sync.Mutex, error)

GetLock retrieve a lock for a given key

func (*StripedMutex) Lock

func (m *StripedMutex) Lock(key string)

Lock acquire lock for a given key

func (*StripedMutex) Unlock

func (m *StripedMutex) Unlock(key string)

Unlock release lock for a given key

Jump to

Keyboard shortcuts

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