面试题答案
一键面试-
实现方式阐述: 可以使用
sync.RWMutex
来实现线程安全的map。sync.RWMutex
提供了读写锁,允许多个读操作同时进行,而写操作时会独占锁,从而保证map操作的线程安全性。 -
核心代码示例:
package main
import (
"fmt"
"sync"
)
type SafeMap struct {
mu sync.RWMutex
data map[string]interface{}
}
// Set 设置键值对
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
}
// Get 获取键对应的值
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
}
// Delete 删除键值对
func (sm *SafeMap) Delete(key string) {
sm.mu.Lock()
defer sm.mu.Unlock()
if sm.data == nil {
return
}
delete(sm.data, key)
}
可以这样使用:
func main() {
safeMap := SafeMap{}
var wg sync.WaitGroup
wg.Add(2)
go func() {
safeMap.Set("key1", "value1")
wg.Done()
}()
go func() {
value, exists := safeMap.Get("key1")
fmt.Printf("Get key1: value = %v, exists = %v\n", value, exists)
wg.Done()
}()
wg.Wait()
}