Sobes.tech
Junior — Middle

How to synchronize access to a shared resource using a Map structure and Mutex mechanism?

sobes.tech AI

Answer from AI

In Go, a mutex (sync.Mutex) is usually used to synchronize access to a shared Map structure, since maps are not thread-safe.

Example:

import (
    "sync"
)

var (
    mu sync.Mutex
    sharedMap = make(map[string]int)
)

func writeToMap(key string, value int) {
    mu.Lock()           // lock access
    sharedMap[key] = value
    mu.Unlock()         // unlock
}

func readFromMap(key string) (int, bool) {
    mu.Lock()
    val, ok := sharedMap[key]
    mu.Unlock()
    return val, ok
}

Thus, before reading or writing to the map, we acquire the mutex to prevent data races and ensure correct operation in a concurrent environment.

How to synchronize access to a shared resource using… - sobes.tech