脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Golang - 快速解决Golang Map 并发读写安全的问题

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

2021-03-17 00:57追风2019 Golang

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

一、错误案例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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 并发写会导致这个错误? 网络上的相关文章也大都有说明。

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

四、解决方案

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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在并发情况下,只读是线程安全的,同时读写线程不安全。

示例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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结构如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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使用示例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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 并发读写安全的问题

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

原文链接:https://blog.csdn.net/createno_1/article/details/106729583

延伸 · 阅读

精彩推荐
  • GolangGolang 语言极简类型转换库cast的使用详解

    Golang 语言极简类型转换库cast的使用详解

    本文我们通过 cast.ToString() 函数的使用,简单介绍了cast 的使用方法,除此之外,它还支持很多其他类型,在这没有多多介绍,对Golang 类型转换库 cast相关知...

    Golang语言开发栈6112021-12-02
  • GolangGO语言字符串处理Strings包的函数使用示例讲解

    GO语言字符串处理Strings包的函数使用示例讲解

    这篇文章主要为大家介绍了GO语言字符串处理Strings包的函数使用示例讲解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加...

    Jeff的技术栈6882022-04-14
  • GolangGolang实现四种负载均衡的算法(随机,轮询等)

    Golang实现四种负载均衡的算法(随机,轮询等)

    本文介绍了示例介绍了Golang 负载均衡的四种实现,主要包括了随机,轮询,加权轮询负载,一致性hash,感兴趣的小伙伴们可以参考一下...

    Gundy_8442021-08-09
  • Golang深入浅析Go中三个点(...)用法

    深入浅析Go中三个点(...)用法

    这篇文章主要介绍了深入浅析Go中三个点(...)用法,需要的朋友可以参考下...

    踏雪无痕SS6472021-11-17
  • GolangGo语言range关键字循环时的坑

    Go语言range关键字循环时的坑

    今天小编就为大家分享一篇关于Go语言range关键字循环时的坑,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来...

    benben_20154202020-05-23
  • GolangGo语言基础单元测试与性能测试示例详解

    Go语言基础单元测试与性能测试示例详解

    这篇文章主要为大家介绍了Go语言基础单元测试与性能测试示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助祝大家多多进步...

    枫少文7812021-12-05
  • GolangGo语言实现自动填写古诗词实例代码

    Go语言实现自动填写古诗词实例代码

    这篇文章主要给大家介绍了关于Go语言实现自动填写古诗词的相关资料,这是最近在项目中遇到的一个需求,文中通过示例代码介绍的非常详细,需要的朋...

    FengY5862020-05-14
  • Golanggo语言获取系统盘符的方法

    go语言获取系统盘符的方法

    这篇文章主要介绍了go语言获取系统盘符的方法,涉及Go语言调用winapi获取系统硬件信息的技巧,具有一定参考借鉴价值,需要的朋友可以参考下 ...

    无尽海3862020-04-24