Sobes.tech
Junior — Middle

Kaip užtikrinti „Map“ objekto srautų saugumą naudojant „Mutex“ tipo užrakinimo mechanizmą?

sobes.tech AI

Atsakymas iš AI

Go kalboje, norint užtikrinti map objekto srautą saugumą, galima naudoti mutexą (sync.Mutex). Kadangi standartinis map nėra saugus kelių srautų atžvilgiu, skaitymo ir rašymo operacijos turi būti apsaugotos užraktu.

Pavyzdys:

import (
    "sync"
)

type SafeMap struct {
    mu sync.Mutex
    m  map[string]int
}

func NewSafeMap() *SafeMap {
    return &SafeMap{
        m: make(map[string]int),
    }
}

func (s *SafeMap) Get(key string) (int, bool) {
    s.mu.Lock()
    defer s.mu.Unlock()
    val, ok := s.m[key]
    return val, ok
}

func (s *SafeMap) Set(key string, value int) {
    s.mu.Lock()
    defer s.mu.Unlock()
    s.m[key] = value
}

func (s *SafeMap) Delete(key string) {
    s.mu.Lock()
    defer s.mu.Unlock()
    delete(s.m, key)
}

Šiuo būdu, prieš kiekvieną operaciją su map, užrakinamas mutex, kas užkerta kelią kelių goroutine'ų vienalaikiam prieigai ir išvengia lenktynių sąlygų.