locks

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2024 License: MIT Imports: 3 Imported by: 1

README

Go Locks

CI

A simple library that provides pools of locks for Go. It is useful when you need to lock on a resource that cannot carry its lock. Such as files, network connections, etc.

Install

go get github.com/DaanV2/go-locks

Usage

package main

import (
    "fmt"
    "github.com/DaanV2/go-locks"
)

func main() {
    pool := locks.NewPool(100)

    lock := pool.GetLock(uint64)
    lock.Lock()
    defer lock.Unlock()

    // Do something with the resource

    // For files:
    key := locks.KeyForString("file.txt")
    lock := pool.GetLock(key)
    lock.Lock()
    defer lock.Unlock()
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func KeyForBytes

func KeyForBytes(b []byte) uint64

KeyForBytes returns a key for a byte slice

func KeyForString

func KeyForString(s string) uint64

KeyForString returns a key for a string

Types

type Pool

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

Pool is a pool of locks that can be used to lock based on a key.

func NewPool

func NewPool(amount int) *Pool

NewPool creates a new pool of locks, where amount is the number of locks to create. It returns an error if the amount is less than or equal to 0. The ideal amount of locks is dependent on the number of threads. With a factor that depends on the amount of collision you want per lock. Example:

threads := 7
// Collision of 25% per lock
amount := threads * (100 / 25) // => 7 * 4 = 28

func (*Pool) GetLock

func (p *Pool) GetLock(key uint64) *sync.Mutex

GetLock returns a lock from the pool based on the key. The key is provided to ensure that the same lock is always returned for the same key. And can be any value. Example:

lock := pool.GetLock(1)
lock = pool.GetLock(987654321)

func (*Pool) Len added in v1.0.2

func (p *Pool) Len() int

Len returns the amount of locks in the pool.

type RWPool

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

func NewRWPool

func NewRWPool(amount int) *RWPool

NewRWPool creates a new pool of locks, where amount is the number of locks to create. Instead of mutexes, it uses RWMutexes.

func (*RWPool) GetLock

func (p *RWPool) GetLock(key uint64) *sync.RWMutex

GetLock returns a lock from the pool based on the key. The key is provided to ensure that the same lock is always returned for the same key. And can be any value. Example:

lock := pool.GetLock(1)
lock = pool.GetLock(987654321)

func (*RWPool) Len added in v1.0.2

func (p *RWPool) Len() int

Len returns the amount of locks in the pool.

Jump to

Keyboard shortcuts

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