并发安全Map需保证多goroutine下数据一致性,Go原生map非并发安全。可通过sync.Mutex加锁实现,但高并发性能差;读多写少时用sync.RWMutex可提升性能,允许多个读、单个写;sync.Map为官方提供的读多写少优化方案,内部用read/dirty双map减少锁竞争,适用key稳定的场景。选择方案需根据读写比例和场景权衡,避免忘记加锁、死锁或误用sync.Map导致性能下降。还可通过channel信号量控制并发访问量,避免锁竞争。

并发安全的Map,简单来说,就是在多个goroutine同时读写Map时,保证数据的一致性和正确性。Golang内置的Map不是并发安全的,直接并发读写会引发panic。
解决方案:
sync.Mutex
sync.RWMutex
sync.Map
sync.Mutex
最直接的方法就是用一个互斥锁保护Map的读写操作。
package main
import (
"fmt"
"sync"
)
type ConcurrentMap struct {
sync.Mutex
data map[string]interface{}
}
func NewConcurrentMap() *ConcurrentMap {
return &ConcurrentMap{
data: make(map[string]interface{}),
}
}
func (m *ConcurrentMap) Set(key string, value interface{}) {
m.Lock()
defer m.Unlock()
m.data[key] = value
}
func (m *ConcurrentMap) Get(key string) (interface{}, bool) {
m.Lock()
defer m.Unlock()
val, ok := m.data[key]
return val, ok
}
func (m *ConcurrentMap) Delete(key string) {
m.Lock()
defer m.Unlock()
delete(m.data, key)
}
func main() {
cmap := NewConcurrentMap()
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
cmap.Set(fmt.Sprintf("key-%d", i), i)
}(i)
}
wg.Wait()
for i := 0; i < 100; i++ {
val, ok := cmap.Get(fmt.Sprintf("key-%d", i))
if ok {
fmt.Printf("key-%d: %v\n", i, val)
}
}
}这里,
ConcurrentMap
sync.Mutex
map[string]interface{}立即学习“go语言免费学习笔记(深入)”;
sync.RWMutex
当读操作远多于写操作时,
sync.RWMutex
package main
import (
"fmt"
"sync"
"time"
)
type ConcurrentMap struct {
sync.RWMutex
data map[string]interface{}
}
func NewConcurrentMap() *ConcurrentMap {
return &ConcurrentMap{
data: make(map[string]interface{}),
}
}
func (m *ConcurrentMap) Set(key string, value interface{}) {
m.Lock() // 使用写锁
defer m.Unlock()
m.data[key] = value
}
func (m *ConcurrentMap) Get(key string) (interface{}, bool) {
m.RLock() // 使用读锁
defer m.RUnlock()
val, ok := m.data[key]
return val, ok
}
func (m *ConcurrentMap) Delete(key string) {
m.Lock() // 使用写锁
defer m.Unlock()
delete(m.data, key)
}
func main() {
cmap := NewConcurrentMap()
var wg sync.WaitGroup
// 模拟大量读操作
for i := 0; i < 100; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
for j := 0; j < 1000; j++ {
_, _ = cmap.Get(fmt.Sprintf("key-%d", i)) // 忽略返回值
time.Sleep(time.Microsecond) // 模拟读操作耗时
}
}(i)
}
// 模拟少量写操作
for i := 0; i < 10; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
cmap.Set(fmt.Sprintf("key-%d", i), i)
time.Sleep(time.Millisecond * 10) // 模拟写操作耗时
}(i)
}
wg.Wait()
fmt.Println("Finished")
}可以看到,
Set
Delete
Lock
Unlock
Get
RLock
RUnlock
sync.Map
sync.Map
sync.Map
read
dirty
read
read
read
dirty
dirty
read
dirty
package main
import (
"fmt"
"sync"
)
func main() {
var sm sync.Map
// 存储数据
sm.Store("name", "Alice")
sm.Store("age", 30)
// 加载数据
if name, ok := sm.Load("name"); ok {
fmt.Println("Name:", name)
}
// 删除数据
sm.Delete("age")
// 遍历数据
sm.Range(func(key, value interface{}) bool {
fmt.Printf("Key: %v, Value: %v\n", key, value)
return true // 继续遍历
})
// LoadOrStore
actual, loaded := sm.LoadOrStore("city", "New York")
fmt.Printf("City: %v, Loaded: %v\n", actual, loaded)
actual, loaded = sm.LoadOrStore("name", "Bob") // Key already exists
fmt.Printf("Name: %v, Loaded: %v\n", actual, loaded)
}sync.Map
Load
Store
Delete
Range
LoadOrStore
sync.Map
dirty
选择哪种实现方式,取决于具体的应用场景。
sync.Mutex
sync.RWMutex
sync.Map
需要注意的是,
sync.Map
sync.Map
sync.Map
sync.Map
sync.Map
Range
除了锁之外,还可以使用channel来实现并发控制。 例如,可以使用一个buffered channel来限制同时访问Map的goroutine数量。
package main
import (
"fmt"
"sync"
)
func main() {
// 创建一个 buffered channel,容量为 10
semaphore := make(chan struct{}, 10)
data := make(map[int]int)
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
// 获取信号量,如果 channel 已满,则阻塞
semaphore <- struct{}{}
// 访问共享资源
data[i] = i * 2
fmt.Printf("Writing: key=%d, value=%d\n", i, data[i])
// 释放信号量
<-semaphore
}(i)
}
wg.Wait()
fmt.Println("Finished writing.")
for k, v := range data {
fmt.Printf("key=%d, value=%d\n", k, v)
}
}这种方法可以避免锁的竞争,但需要仔细设计channel的容量,以达到最佳的性能。 此外,还可以使用原子操作来实现一些简单的并发控制,例如原子计数器。
总而言之,选择合适的并发控制手段需要根据具体的应用场景进行权衡。
以上就是Golang并发安全的Map使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号