MST

星途 面试题库

面试题:Go语言中如何初步保障Map并发安全

在Go语言里,原生的Map不是并发安全的。请简述一种常见的能够初步保障Map并发安全的方法,并给出简单的代码示例。
30.9万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试

常见方法

使用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 {}
}