快速解决Golang Map 并发读写安全的问题

这篇文章主要介绍了快速解决Golang Map 并发读写安全的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

一、错误案例

package main
import (
"fmt"
"time"
)
var TestMap map[string]string
func init() {
TestMap = make(map[string]string, 1)
}
func main() {
for i := 0; i < 1000; i++ {
go Write("aaa")
go Read("aaa")
go Write("bbb")
go Read("bbb")
}
time.Sleep(5 * time.Second)
}
func Read(key string) {
fmt.Println(TestMap[key])
}
func Write(key string) {
TestMap[key] = key
}

上面代码执行大概率出现报错:fatal error: concurrent map writes

二、问题分析

网上关于 golang 编程中 map 并发读写相关的资料很多,但总是都说成 并发读写 造成上面的错误,到底是 并发读 还是 并发写 造成的,这个很多资料都没有说明。

我们把上面的案例分别在循环中注释 Read 和 Write 函数的调用,分别测试 并发读 和 并发写;

循环次数分别测试了 100、1 w、100 w 次,并发读操作绝对不会报上面的错,而并发写基本都会报错。

因此,这个错误主要原因是:map 并发写。

三、问题原因

因为 map 变量为 指针类型变量,并发写时,多个协程同时操作一个内存,类似于多线程操作同一个资源会发生竞争关系,共享资源会遭到破坏,因此golang 出于安全的考虑,抛出致命错误:fatal error: concurrent map writes。

四、解决方案

网上各路资料解决方案较多,主要思路是通过加锁保证每个协程同步操作内存。

github 上找到一个 concurrentMap 包,案例代码修改如下:

package main
import (
 "fmt"
 cmap "github.com/orcaman/concurrent-map"
 "time"
)
var TestMap cmap.ConcurrentMap
func init() {
 TestMap = cmap.New()
}
func main() {
 for i := 0; i < 100; i++ {
 go Write("aaa", "111")
 go Read("aaa")
 go Write("bbb", "222")
 go Read("bbb")
 }
 time.Sleep(5 * time.Second)
}
func Read(key string) {
 if v, ok := TestMap.Get(key); ok {
 fmt.Printf("键值为 %s 的值为:%s", key, v)
 } else {
 fmt.Printf("键值不存在")
 }
}
func Write(key string, value string) {
 TestMap.Set(key, value)
}

五、思考总结

因为我是以 php 打开的编程世界,PHP 语言只有单线程,且不涉及指针操作,变量类型也是弱变量,以 PHP 编程思维刚开始接触 Golang 时还比较容易上手,但越往后,语言的特性区别就体现得越来越明显,思维转变就越来越大,对我来说是打开了一个新世界。

像本文出现的错误案例,也是因为自己没有多线程编程的思维基础,导致对这种问题不敏感,还是花了蛮多时间理解的。希望对和我有相似学习路线的朋友提供到一些帮助。

补充:Golang Map并发处理机制(sync.Map)

Go语言中的Map在并发情况下,只读是线程安全的,同时读写线程不安全。

示例:

package main 
import (
 "fmt"
)
var m = make(map[int]int)
func main() {
 //写入操作
 i:=0
 go func() {
 for{
 i++
 m[1]=i
 }
 
 }()
 //读操作
 go func() {
 for{
 fmt.Println(m[1])
 }
 
 }()
 //无限循环,让并发程序在后台运行
 for {
 ;
 }
}

快速解决Golang Map 并发读写安全的问题

从以上示例可以看出,不断地对map进行读和写,会出现错误。主要原因是对map进行读和写发生了竞态问题。map内部会对这种并发操作进行检查并提前发现。

如果确实需要对map进行并发读写操作,可以采用加锁机制、channel同步机制,但这样性能并不高。

Go语言在1.9版本中提供了一种效率较高的并发安全的sync.Map。

sync.Map结构如下:

The zero Map is empty and ready for use. A Map must not be copied after first use.
type Map struct {
 mu Mutex
 misses int
}
 
// Load returns the value stored in the map for a key, or nil if no
// value is present.
// The ok result indicates whether value was found in the map.
func (m *Map) Load(key interface{}) (value interface{}, ok bool) { 
}
 
// Store sets the value for a key.
func (m *Map) Store(key, value interface{}) {
 
}
// LoadOrStore returns the existing value for the key if present.
// Otherwise, it stores and returns the given value.
// The loaded result is true if the value was loaded, false if stored.
func (m *Map) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool) { 
}
 
// Delete deletes the value for a key.
func (m *Map) Delete(key interface{}) { 
} 
 
// Range calls f sequentially for each key and value present in the map.
// If f returns false, range stops the iteration.
//
// Range does not necessarily correspond to any consistent snapshot of the Map's
// contents: no key will be visited more than once, but if the value for any key
// is stored or deleted concurrently, Range may reflect any mapping for that key
// from any point during the Range call.
//
// Range may be O(N) with the number of elements in the map even if f returns
// false after a constant number of calls.
func (m *Map) Range(f func(key, value interface{}) bool) { 
}
 
func (m *Map) missLocked() {
 
}
 
func (m *Map) dirtyLocked() {
 
}

其实,sync.Map内部还是进行了加锁机制,不过进行了一定的优化。

sync.Map使用示例:

package main 
import (
 "fmt"
 "sync"
 "time"
)
 
var m1 sync.Map 
func main() {
 i := 0
 go func() {
 for {
 i++
 m1.Store(1, i)
 time.Sleep(1000)
 }
 }()
 go func() {
 for{
 time.Sleep(1000)
 fmt.Println(m1.Load(1))
 }
 
 }()
 for {
 ;
 }
}

成功运行效果如下:

快速解决Golang Map 并发读写安全的问题

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。如有错误或未考虑完全的地方,望不吝赐教。

如有侵权,请联系QQ:279390809 电话:15144810328