Sobes.tech
Junior — Middle

How to ensure safe access to a map in a multithreaded environment?

sobes.tech AI

Answer from AI

In Go, to safely access a map in a multithreaded environment, synchronization must be used because a map is not a thread-safe data structure. The most common way is to use a mutex (sync.Mutex or sync.RWMutex) to lock access during reading and writing.

Example using sync.RWMutex:

import (
    "sync"
)

var (
    m = make(map[string]int)
    mu sync.RWMutex
)

func read(key string) int {
    mu.RLock()         // lock for reading
    defer mu.RUnlock()
    return m[key]
}

func write(key string, value int) {
    mu.Lock()          // lock for writing
    defer mu.Unlock()
    m[key] = value
}

Go also has the type sync.Map, which implements a thread-safe map with optimizations for frequent read operations. It can be used if strict typing is not required and simplicity is desired:

import "sync"

var m sync.Map

m.Store("key", 42)          // store
value, ok := m.Load("key")  // load

Thus, for safe access to a map in a multithreaded environment, use mutexes or sync.Map.

How to ensure safe access to a map in a multithreaded… - sobes.tech