Concurrent-Safe Map Container in Go

Jerry An
2 min readOct 22, 2023
Photo by Georg Bommeli on Unsplash

The “concurrent map writes” problem occurs when multiple goroutines try to write to a map concurrently, causing race conditions and unpredictable behavior.

Here we list some solutions to this problem.

Use a mutex to synchronize access to the map

This involves locking the mutex before reading or writing to the map, and unlocking it afterwards. This ensures that only one goroutine can access the map at a time.

var (
m = make(map[string]int)
mutex = sync.Mutex{}
)

func readFromMap(key string) int {
mutex.Lock()
defer mutex.Unlock()
return m[key]
}

func writeToMap(key string, value int) {
mutex.Lock()
defer mutex.Unlock()
m[key] = value
}

Use a read-write mutex to allow multiple readers to access the map at the same time, but only one writer.

This involves locking the read-write mutex for reading before reading from the map and unlocking it afterward. For writing, the mutex is locked for writing, which blocks all readers and writers until the writing is complete.

var (
m = make(map[string]int)
rwMutex = sync.RWMutex{}
)

func readFromMap(key string) int {
rwMutex.RLock()
defer rwMutex.RUnlock()…

--

--