Назад к вопросам
Middle+
4
Реализуйте кэш на основе map[string]any с конструктором, методом Get и методом Set, с учётом конкурентного доступа (Mutex)
Компании, где спрашивали
BGStaff
Ответ от нейросети
sobes.tech AI
go package cache
import "sync"
type Cache struct { mu sync.Mutex store map[string]any }
func NewCache() *Cache { return &Cache{ store: make(map[string]any), } }
func (c *Cache) Get(key string) (any, bool) { c.mu.Lock() defer c.mu.Unlock() val, ok := c.store[key] return val, ok }
func (c *Cache) Set(key string, value any) { c.mu.Lock() defer c.mu.Unlock() c.store[key] = value }
В этом примере структура Cache содержит map и mutex для защиты от конкурентного доступа. Методы Get и Set блокируют mutex на время операции, чтобы избежать гонок данных.