syncmap

package module
v0.0.0-...-6cbbb21 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2023 License: BSD-3-Clause Imports: 1 Imported by: 2

README

syncmap provides a simple generic goroutine safe map type

Documentation

Overview

syncmap provides a simple generic goroutine safe map type

// If you plan on doing multiple operations on the map
// which have to be synchronized use the WithLock method!
m := syncmap.New[string, int]()
m.Set("a", 1)
m.Set("b", 2)
m.Set("c", 3)
if v, ok := m.Get("a"); ok {
    fmt.Println("found a! it's value is:", v)
}

m.Delete("a") // delete a single key
m.Delete("b", "c") // delete a bunch of keys at once
m.Reset() // clear the map

// Run multiple operations in sync
m.WithLock(func(lm LockedMap[string, int]) {
    if value, ok := lm.Get("a"); ok {
        lm.Set("b", value)
    }
})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type LockedMap

type LockedMap[K comparable, V any] interface {
	Set(key K, value V)
	Get(key K) (value V, found bool)
	Delete(keys ...K)
	Reset()
	Len() int
	Keys() []K
}

LockedMap is a map which is already locked. It's Methods do not lock and are therefore not goroutine safe. You only use this within the WithLock method of Map.

type Map

type Map[K comparable, V any] interface {
	Set(key K, value V)
	Get(key K) (value V, found bool)
	Delete(keys ...K)
	// Reset removes all elements from the map
	Reset()
	Len() int

	Keys() []K

	// WithLock provides a way to run multiple operations on a map
	// by holding the lock for the entire time of the callback
	//
	//  m := syncmap.New[string, int]()
	//
	//  // BAD BAD BAD - This is a possible race condition
	//  // another goroutine might alter m between the calls to Get() and Set()
	//  if value, ok := m.Get("a"); ok {
	//      m.Set("b", value)
	//  }
	//
	//  // Good
	//  // WithLock guarantees that all operations within the callback
	//  // are run within a single lock
	//  m.WithLock(func(lm LockedMap[string, int]) {
	//      if value, ok := lm.Get("a"); ok {
	//          lm.Set("b", value)
	//      }
	//  })
	//
	WithLock(func(LockedMap[K, V]))
}

Map is a generic, goroutine safe, maplike container. It uses a mutex to be goroutine safe.

func New

func New[K comparable, V any](capacity ...int) Map[K, V]

New creates a new map with an optional initial capacity

Jump to

Keyboard shortcuts

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