Documentation
¶
Overview ¶
Mutex: Value, Numeric, and Map using Generics ¶
Package mutex provides a collection of thread-safe data structures using generics in Go. It offers a Value type for lock-protected values, a Numeric type for thread-safe numeric operations, and a Map type for a concurrent map with type safety. These structures are designed to be easy to use, providing a simple and familiar interface similar to well known atomic.Value and sync.Map, but with added type safety and the flexibility of generics. The package aims to simplify concurrent programming by ensuring safe access to shared data and reducing the boilerplate code associated with mutexes.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Map ¶ added in v0.1.0
type Map[K comparable, V any] interface { // Load returns the value stored in the map for a key, or nil if no // value is present. // The ok result indicates whether value was found in the map. Load(key K) (v V, ok bool) // Store sets the value for a key. Store(key K, value V) // LoadOrStore returns the existing value for the key if present. // Otherwise, it stores and returns the given value. // The loaded result is true if the value was loaded, false if stored. LoadOrStore(key K, value V) (actual V, loaded bool) // LoadAndDelete deletes the value for a key, returning the previous value if any. // The loaded result reports whether the key was present. LoadAndDelete(key K) (value V, loaded bool) // Delete deletes the value for a key. Delete(key K) // Swap swaps the value for a key and returns the previous value if any. // The loaded result reports whether the key was present. Swap(key K, value V) (previous V, loaded bool) // CompareAndSwap swaps the old and new values for key // if the value stored in the map is equal to old. // // Returns true if the swap was performed. // // ! this function uses reflect.DeepEqual to compare the values. CompareAndSwap(key K, old, new V) bool // CompareAndDelete deletes the entry for key if its value is equal to old. // // If there is no current value for key in the map, CompareAndDelete // returns false (even if the old value is the nil interface value). // // ! this function uses reflect.DeepEqual to compare the values. CompareAndDelete(key K, old V) (deleted bool) // Range calls f sequentially for each key and value present in the map. // If f returns false, range stops the iteration. // // Range does not necessarily correspond to any consistent snapshot of the Map's // contents: no key will be visited more than once, but if the value for any key // is stored or deleted concurrently (including by f), Range may reflect any // mapping for that key from any point during the Range call. Range does not // block other methods on the receiver; even f itself may call any method on m. // // Range may be O(N) with the number of elements in the map even if f returns // false after a constant number of calls. Range(f func(K, V) bool) // Update allows the caller to change the value associated with the key atomically guaranteeing that the value would not be changed by another goroutine during the operation. // // ! Do not invoke any Map functions within 'f' to prevent a deadlock. Update(key K, f func(V, bool) V) // UpdateRange is a thread-safe version of Range that locks the map for the duration of the iteration and allows for the modification of the values. // If f returns false, UpdateRange stops the iteration, without updating the corresponding value in the map. // // ! Do not invoke any Map functions within 'f' to prevent a deadlock. UpdateRange(f func(K, V) (V, bool)) // Exclusive provides a way to perform operations on the map ensuring that no other operation is performed on the map during the execution of the function. // // ! Do not invoke any Map functions within 'f' to prevent a deadlock. Exclusive(f func(m map[K]V)) // Clear removes all items from the map. Clear() // Has returns true if the map contains the key. Has(key K) bool // Keys returns a slice of all the keys present in the map, an empty slice is returned if the map is empty. Keys() (keys []K) // Values returns a slice of all the values present in the map, an empty slice is returned if the map is empty. Values() (values []V) // Entries returns two slices, one containing all the keys and the other containing all the values present in the map. Entries() (keys []K, values []V) // Len returns the number of unique keys in the map. Len() (n int) }
Map is a generic interface that provides a way to interact with the map. its interface is identical to sync.Map and so are function definition and behaviour.
Example ¶
package main import ( "fmt" "strconv" "sync" "github.com/thetechpanda/mutex" ) func main() { m := mutex.NewMap[string, int]() // create a wait group to synchronize goroutines var wg sync.WaitGroup // the following two goroutine will store values from 0 to 999 using the keys "0" to "999" wg.Add(1) go func() { defer wg.Done() for i := 0; i < 1000; i++ { m.Store(strconv.Itoa(i), i) } }() // the following two goroutine will store values from 0 to -999 using the keys "0" to "999" wg.Add(1) go func() { defer wg.Done() for i := 0; i < 1000; i++ { m.Store(strconv.Itoa(i), -i) } }() // wait for goroutines to finish wg.Wait() v, ok := m.Load("123") // v is int fmt.Println("v =", v, ", ok =", ok) // "v = -123 , ok = true" or "v = 123 , ok = true" }
Output:
func NewMap ¶ added in v0.1.0
func NewMap[K comparable, V any]() Map[K, V]
NewMap returns an empty Mutex Map.
func NewMapWithValue ¶ added in v0.1.0
func NewMapWithValue[K comparable, V any](m map[K]V) Map[K, V]
NewMapWithValue returns a Mutex Map with the provided map. m is copied into the Mutex Map.
type Numeric ¶
type Numeric[V uint | uint8 | uint16 | uint32 | uint64 | int | int8 | int16 | int32 | int64 | float32 | float64 | complex64 | complex128] interface { Value[V] // Add adds delta to the value stored. Add(delta V) V }
Numeric is an interface that extends Value with an Add method. The value stored must be a numeric type.
Example ¶
package main import ( "fmt" "sync" "github.com/thetechpanda/mutex" ) func main() { // create a new Value with initial value 0 m := mutex.NewNumeric[int]() m.Store(0) // create a wait group to synchronize goroutines var wg sync.WaitGroup // the following two goroutine add 1 to the value 1000 times wg.Add(1) go func() { defer wg.Done() for i := 0; i < 1000; i++ { m.Add(1) } }() // the following two goroutine subtract 1 to the value 1000 times wg.Add(1) go func() { defer wg.Done() for i := 0; i < 1000; i++ { m.Add(-1) } }() // wait for goroutines to finish wg.Wait() v, ok := m.Load() fmt.Println("value =", v, ", ok =", ok) // value = 0 , ok = true }
Output:
type Value ¶
type Value[V any] interface { // Load returns the value stored, or zero value if no // value is present. // The ok result indicates whether value was set. Load() (v V, ok bool) // Store sets the value. Store(value V) // LoadOrStore returns the existing value if present. // Otherwise, it stores and returns the given value. // The loaded result is true if the value was loaded, false if stored. LoadOrStore(value V) (actual V, loaded bool) // Swap swaps the value for a key and returns the previous value if any. // The loaded result reports whether the key was present. Swap(value V) (previous V, loaded bool) // CompareAndSwap swaps the old and new values // if the value stored in the map is equal to old. // // Returns true if the swap was performed. // // ! this function uses reflect.DeepEqual to compare the values. CompareAndSwap(old, new V) bool // return true if the value is a zero value (not set) IsZero() bool // Exclusive executes the function f exclusively, ensuring that no other goroutine is accessing the value. // // The function f is passed the current value and a boolean indicating whether the value is set. // The function f should return the new value to be stored. // // ! Do not invoke any Value or Numeric functions within 'f' to prevent a deadlock. Exclusive(f func(v V, ok bool) V) V // Clear removes the value from the store. Clear() }
Value is an interface that represents a thread-safe value store. It provides methods to load, store, and manipulate the stored value. The value can be of any type specified by the type parameter V. Pay attention when using pointer types as modifications to the value directly could lead to concurrency issues.
Example ¶
package main import ( "fmt" "strconv" "sync" "github.com/thetechpanda/mutex" ) func main() { // create a new Value with initial value 0 m := mutex.NewValue[string]() m.Store("") // create a wait group to synchronize goroutines var wg sync.WaitGroup // the following two goroutine will store values from 0 to 999 wg.Add(1) go func() { defer wg.Done() for i := 0; i < 1000; i++ { m.Store(strconv.Itoa(i)) } }() // the following two goroutine will store values from 0 to -999 wg.Add(1) go func() { defer wg.Done() for i := 0; i < 1000; i++ { m.Store(strconv.Itoa(-i)) } }() // wait for goroutines to finish wg.Wait() // value is either "-999" or "999" v, ok := m.Load() fmt.Println("value =", v, ", ok =", ok) // "value = -999 , ok = true" or "value = 999 , ok = true" }
Output:
func NewWithValue ¶
NewWithValue returns a new Value, set to the specified value.