面试题答案
一键面试常见方法
使用sync.RWMutex
来保障Map的并发安全。读操作时可以允许多个协程同时进行,写操作时则需要独占访问,以此来避免数据竞争。
代码示例
package main
import (
"fmt"
"sync"
)
type SafeMap struct {
mu sync.RWMutex
data map[string]interface{}
}
func (sm *SafeMap) Set(key string, value interface{}) {
sm.mu.Lock()
defer sm.mu.Unlock()
if sm.data == nil {
sm.data = make(map[string]interface{})
}
sm.data[key] = value
}
func (sm *SafeMap) Get(key string) (interface{}, bool) {
sm.mu.RLock()
defer sm.mu.RUnlock()
if sm.data == nil {
return nil, false
}
value, exists := sm.data[key]
return value, exists
}
func main() {
safeMap := SafeMap{}
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(index int) {
defer wg.Done()
key := fmt.Sprintf("key%d", index)
safeMap.Set(key, index)
}(i)
}
go func() {
wg.Wait()
for i := 0; i < 10; i++ {
key := fmt.Sprintf("key%d", i)
value, exists := safeMap.Get(key)
if exists {
fmt.Printf("Key: %s, Value: %v\n", key, value)
}
}
}()
select {}
}