GO · 컬렉션
맵 동시성 문제
Go의 map은 동시 읽기/쓰기에 안전하지 않습니다. sync.Mutex나 sync.RWMutex로 보호해야 합니다.
컬렉션중급mapconcurrencymutexrwmutexrace
핵심 설명
Go의 map은 동시 읽기/쓰기에 안전하지 않습니다. sync.Mutex나 sync.RWMutex로 보호해야 합니다.
Go code
package main
import (
"fmt"
"sync"
)
// RWMutex로 보호된 맵
type SafeCounter struct {
mu sync.RWMutex
m map[string]int
}
func (c *SafeCounter) Inc(key string) {
c.mu.Lock()
defer c.mu.Unlock()
c.m[key]++
}
func (c *SafeCounter) Get(key string) int {
c.mu.RLock() // 읽기 전용 잠금
defer c.mu.RUnlock()
return c.m[key]
}
func main() {
counter := SafeCounter{m: make(map[string]int)}
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
counter.Inc("visits")
}()
}
wg.Wait()
fmt.Println("visits:", counter.Get("visits")) // 1000
}학습 팁
읽기가 많고 쓰기가 적은 경우 sync.RWMutex가 sync.Mutex보다 효율적입니다.
주의할 점
map을 동시에 읽고 쓰면 fatal error: concurrent map read and map write 런타임 에러가 발생합니다.
자주 묻는 질문
맵 동시성 문제란 무엇인가요?
Go의 map 은 동시 읽기/쓰기에 안전하지 않습니다. sync.Mutex 나 sync.RWMutex 로 보호해야 합니다.
맵 동시성 문제 학습 시 주의할 점은 무엇인가요?
map을 동시에 읽고 쓰면 fatal error: concurrent map read and map write 런타임 에러가 발생합니다.
Continue Learning
Go 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.