Sobes.tech
Middle+

How to combine the map and mutex logically?

sobes.tech AI

Answer from AI

To create a thread-safe map.

When multiple goroutines access a map simultaneously, data races can occur. A mutex, or an RWMutex for more fine-grained control, is used to synchronize access. A lock is applied before reading or writing data to the map, and released after the operation.

Example with sync.RWMutex:

package main

import (
	"sync"
)

// SafeMap - thread-safe map
type SafeMap struct {
	mu sync.RWMutex // mutex for protecting the map
	m  map[string]string // the map itself
}

// NewSafeMap - creates a new instance of SafeMap
func NewSafeMap() *SafeMap {
	return &SafeMap{
		m: make(map[string]string),
	}
}

// Set - writes a value to the map with a write lock
func (sm *SafeMap) Set(key, value string) {
	sm.mu.Lock() // acquire write lock
	defer sm.mu.Unlock() // release lock after function completes
	sm.m[key] = value
}

// Get - reads a value from the map with a read lock
func (sm *SafeMap) Get(key string) (string, bool) {
	sm.mu.RLock() // acquire read lock (allows multiple goroutines to read simultaneously)
	defer sm.mu.RUnlock() // release lock
	val, ok := sm.m[key]
	return val, ok
}

// Delete - removes an element from the map with a write lock
func (sm *SafeMap) Delete(key string) {
	sm.mu.Lock() // acquire write lock
	defer sm.mu.Unlock() // release lock
	delete(sm.m, key)
}

Thus, the mutex wraps access to the map, ensuring that at any given moment only one goroutine can modify the map (using Lock/Unlock) or multiple goroutines can read it simultaneously (using RLock/RUnlock for RWMutex).