golang sync.Map 是一个标准库中的一个并发安全的映射类型,特别适用于以下场景


package main
import (
"fmt"
"sync"
)
// A function that simulates a costly computation
func costlyComputation(key string) string {
// Simulate a costly computation
return "Result for " + key
}
func main() {
var cache sync.Map
// Function to get or compute a value
getOrCompute := func(key string) string {
// Try to load the value from the cache
if value, ok := cache.Load(key); ok {
return value.(string)
}
// If the value is not in the cache, compute it
result := costlyComputation(key)
// Store the computed value in the cache
cache.Store(key, result)
return result
}
keys := []string{"a", "b", "a", "c", "b", "d"}
// Simulate multiple concurrent accesses to the cache
var wg sync.WaitGroup
for _, key := range keys {
wg.Add(1)
go func(k string) {
defer wg.Done()
result := getOrCompute(k)
fmt.Printf("Key: %s, Result: %s\n", k, result)
}(key)
}
wg.Wait()
}

浙公网安备 33010602011771号