Sobes.tech
Junior — Middle

Kuidas sünkroneerida juurdepääsu ühisele ressursile, kasutades Map-struktuuri ja Mutex-mehhanismi?

sobes.tech AI

Vastus AI-lt

In Go, to synchronize access to a shared Map structure, a mutex (sync.Mutex) is commonly used because the map is 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
}

This way, before reading or writing to the map, we lock the mutex to prevent race conditions and ensure correct operation in a concurrent environment.