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()
return m[key]
}

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

Use third-party package

gmap is a package in the gf framework for Go that provides a high-performance concurrent-safe map container.

var m = gmap.New(true)

func readFromMap(key string) int {
return m.Get(key).(int)
}

func writeToMap(key string, value int) {
m.Set(key, value)
}

These are just a few solutions for reading from and writing to a map concurrently in Golang. There are many other approaches, and the best solution depends on the specific use case and requirements.

--

--