mutexmap

package module
v1.0.14 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2025 License: MIT Imports: 2 Imported by: 3

README

GitHub Workflow Status (branch) GoDoc Coverage Status Supported Go Versions GitHub Release Go Report Card

MutexMap - A Thread-Safe Map for Go

A thread-safe map implementation for Go, using sync.RWMutex to synchronize access. This package is optimized for scenarios involving concurrent reads and writes, providing efficient and reliable operations for multi-thread applications.

README

中文说明

Overview

Go’s standard map is not safe for concurrent access. This package wraps a map[K]V with sync.RWMutex to provide thread safety. With RWMutex, multiple readers can access the map simultaneously, while writes are synchronized to prevent race conditions.

Key highlights:

  • Thread-safety: Prevents data races in concurrent environments.
  • Efficient Reads: Read operations (Get, Range) are lock-free for other readers.
  • Synchronous Write: Write operations (Set, Delete, Getset) are synchronous.

This package is suitable for use cases requiring frequent reads and occasional writes with a shared map.

Installation

go get github.com/yyle88/mutexmap  

Example Usage

Basic Operations
package main

import (
	"fmt"
	"github.com/yyle88/mutexmap"
)

func main() {
	mp := mutexmap.NewMap[string, int](10)

	mp.Set("key1", 100)
	mp.Set("key2", 200)

	if value, found := mp.Get("key1"); found {
		fmt.Println("Key1 Value:", value)
	}

	mp.Range(func(key string, value int) bool {
		fmt.Println(key, value)
		return true
	})
}  
Using Getset for Cached Initialization
package main

import (
	"fmt"
	"github.com/yyle88/mutexmap"
)

func main() {
	mp := mutexmap.NewMap[string, string](10)

	value, status := mp.Getset("exampleKey", func() string {
		return "This is a computed value"
	})
	fmt.Println("Status:", status, "Value:", value)

	value, status = mp.Getset("exampleKey", func() string {
		return "Another computed value"
	})
	fmt.Println("Status:", status, "Value:", value)
}  

Features

  • Concurrent Access: Allows multiple goroutines to safely read and write to the map.
  • Optimized Reads: Supports simultaneous reads for better performance.
  • Custom Initialization: Use Getset to set a new value only if key does not exist.

Method Summary

Method Description
NewMap[K comparable, V any](cap int) Creates a new Map with an optional initial capacity.
Get(k K) (V, bool) Retrieves the value for the given key. Returns false means the key is not exist in map.
Set(k K, v V) Sets a value for the given key. Overwrites if the key already exists.
Delete(k K) Removes the key-value pair from the map.
Len() int Returns the number of elements in the map.
Range(func(k K, v V) bool) Iterates over all key-value pairs. Stops if the callback returns false.
Getset(k K, func() V) (V, enum) Gets a value or set a value only if it doesn’t exist, ensuring the creation is singleton.

Why Use MutexMap?

  1. Thread Safety: Essential for shared maps in multi-threaded environments.
  2. Efficient Reads: Read lock (RLock) ensures non-blocking reads for other readers.
  3. Write Synchronization: Write lock (Lock) ensures data integrity during modifications.
  4. Flexible Initialization: The Getset method prevents redundant computations.

License

MIT License. See LICENSE.


Contributing

Contributions are welcome! To contribute:

  1. Fork the repo on GitHub (using the webpage interface).
  2. Clone the forked project (git clone https://github.com/yourname/repo-name.git).
  3. Navigate to the cloned project (cd repo-name)
  4. Create a feature branch (git checkout -b feature/xxx).
  5. Stage changes (git add .)
  6. Commit changes (git commit -m "Add feature xxx").
  7. Push to the branch (git push origin feature/xxx).
  8. Open a pull request on GitHub (on the GitHub webpage).

Please ensure tests pass and include relevant documentation updates.


Support

Welcome to contribute to this project by submitting pull requests and reporting issues.

If you find this package valuable, give me some stars on GitHub! Thank you!!!

Thank you for your support!

Happy Coding with this package! 🎉

Give me stars. Thank you!!!

GitHub Stars

starring

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CacheStatus added in v1.0.14

type CacheStatus string
const (
	CacheGet CacheStatus = "GET"
	CacheSet CacheStatus = "SET"
)

type Map

type Map[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Map provides a thread-safe map implementation using a sync.RWMutex. Map 提供了一个使用 sync.RWMutex 的线程安全 map 实现。

func New added in v1.0.13

func New[K comparable, V any]() *Map[K, V]

New creates a new thread-safe map. New 创建线程安全 map。

func NewMap

func NewMap[K comparable, V any](cap int) *Map[K, V]

NewMap creates a new thread-safe map. NewMap 创建线程安全 map。

func (*Map[K, V]) Delete

func (a *Map[K, V]) Delete(k K)

Delete removes the key-value. Delete 移除与指定键关联的键值对。

func (*Map[K, V]) Get

func (a *Map[K, V]) Get(k K) (V, bool)

Get retrieves the value associated with the given key. It returns the value and a boolean indicating whether the key exists. Get 获取与指定键关联的值,它返回值以及一个布尔值,指示键是否存在。

func (*Map[K, V]) Getset

func (a *Map[K, V]) Getset(k K, calculate func() V) (v V, status CacheStatus)

Getset retrieves the value associated with the key, or computes and stores a new value if the key does not exist. It returns the value and a enum indicating whether a new value was created. Getset 获取与键关联的值,如果键不存在,则计算并存储新值。 它返回值以及一个枚举值,指示是否创建了新值。

func (*Map[K, V]) Len

func (a *Map[K, V]) Len() int

Len returns the number of key-value pairs in the map. Len 返回 map 中键值对的数量。

func (*Map[K, V]) Range

func (a *Map[K, V]) Range(run func(k K, v V) bool)

Range iterates over all key-value pairs in the map, applying the given function. If the function returns false, the iteration stops. Range 遍历 map 中的所有键值对,并应用给定的函数。 如果函数返回 false,迭代将停止。

func (*Map[K, V]) Set

func (a *Map[K, V]) Set(k K, v V)

Set inserts or updates the value for the given key into map. Set 插入或更新指定键的值。

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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