"进阶架构师" 微信公众号,欢迎大家订阅、阅读、评论、点赞!!!!
前言
吼吼吼,正如我们之前,简单学习了Map在Go中的初始化以及相关的简单实用。我们今天,来进一步的学习GoLang中Map的迭代遍历。
对于之前没有看到的小伙伴,可以先移步,慢聊Go之Go中的Map|Go主题月
另外,正如我们之前学习Java时,了解到的,如果遍历集合,在多线程环境下,可能会出现意想不到的问题。那么,Go中呢?我们好好学学。
Map容器迭代
要想遍历Go的Map容器,我们可以直接使用For循环,来遍历地图中的所有的可用Key。
为了更好地理解,我们举一个简单的示例。在该示例中,我们在Map中插入一堆条目数据,然后对所有条目进行扫描。
package main
import (
"fmt"
)
func main() {
// Allocate memory for the map
var myMap = make(map[int]string)
myMap[0] = "test"
myMap[2] = "sample"
myMap[1] = "GoLang is Fun!"
// Iterate over all keys
for key, val := range myMap {
fmt.Printf("Key: %d, Value: %s\n", key, val)
}
}
输出结果
Key: 0, Value: test
Key: 2, Value: sample
Key: 1, Value: GoLang is Fun!
在这里,迭代顺序不依赖于任何排序标准,因此,如果在此处获得不同的输出,请不要感到惊讶!这是因为Golang在map内部使用C语言中的哈希表,该哈希表使用哈希函数来索引键。
由于我们的key在这里是整数,所以看起来不错,但是如果要遍历a map[string]string,则顺序将是随机的。
那么,对于有顺序需求的,怎么办呢?
按排序顺序遍历key
为了有序地遍历键,我们可以简单地事先对键进行排序。但是要做到这一点,我们需要额外的空间来存储地图中的键列表。
我们可以通过以下方式实现这一目标:
package main
import (
"fmt"
"sort"
)
func main() {
// Allocate memory for the map
var myMap = make(map[int]string)
myMap[0] = "test"
myMap[2] = "sample"
myMap[1] = "GoLang is Fun!"
// Let's get a slice of all keys
keySlice := make([]int, 0)
for key, _ := range myMap {
keySlice = append(keySlice , key)
}
// Now sort the slice
sort.Ints(keySlice)
// Iterate over all keys in a sorted order
for _, key := range keySlice {
fmt.Printf("Key: %d, Value: %s\n", key, myMap[key])
}
}
我们首先创建所有键的切片,然后使用对其进行排序,sort.Ints()因为我们的地图的格式为map[int]string,所以键是整数。
之后,我们可以遍历排序的切片并使用来获取值myMap[key]。
输出结果
Key: 0, Value: test
Key: 1, Value: GoLang is Fun!
Key: 2, Value: sample
并发Map中读写
到目前为止,我们假设只有一个函数可以访问和修改地图,因此迭代很简单。但是,如果此迭代需要在多个函数中或更具体地在多个goroutine中完成,该怎么办?
让我们举一个例子来研究:
这是一个使用多个goroutines访问和修改global的程序map。所有goroutine都会更新所有键,然后最终对其进行迭代。
我使用了GoRoutines,Defer和WaitGroups等概念。
package main
import (
"fmt"
"strconv"
"sync"
)
// Let's have a global map variable so that all goroutines can easily access it
var myMap map[int]string
func myGoRoutine(id int, numKeys int, wg *sync.WaitGroup) {
defer wg.Done()
for key, _ := range myMap {
myMap[key] = strconv.Itoa(id)
}
for key, value := range myMap {
fmt.Printf("Goroutine #%d -> Key: %d, Value: %s\n", id, key, value)
}
}
func main() {
// Initially set some values
myMap = make(map[int]string)
myMap[0] = "test"
myMap[2] = "sample"
myMap[1] = "GoLang is Fun!"
// Get the number of keys
numKeys := len(myMap)
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go myGoRoutine(i, numKeys, &wg)
}
// Blocking wait
wg.Wait()
// Iterate over all keys
for key, value := range myMap {
fmt.Printf("Key: %d, Value: %s\n", key, value)
}
}
因为goroutine的调度是随机的,结果每个人可能是不同的。结果如下:
Goroutine #2 -> Key: 0, Value: 2
Goroutine #2 -> Key: 2, Value: 0
Goroutine #2 -> Key: 1, Value: 0
Goroutine #1 -> Key: 0, Value: 1
Goroutine #1 -> Key: 2, Value: 1
Goroutine #1 -> Key: 1, Value: 1
Goroutine #0 -> Key: 0, Value: 0
Goroutine #0 -> Key: 2, Value: 1
Goroutine #0 -> Key: 1, Value: 1
Key: 0, Value: 1
Key: 2, Value: 1
Key: 1, Value: 1
由于多个goroutine可能同时读取和写入,这将产生意外的输出。例如,Goroutine 0和2的行为不同,因为Goroutine 0在Goroutine 2可以从它读取之前就已经写入了地图!
这种情况-多个线程(goroutine)可以访问同一内存位置进行读写的情况称为数据竞争条件,即使开发测试运行良好,也很难在生产中检测到。
在这里,我们不能简单地使用normal map。为了解决这个问题,一种方法是通过互斥(mutex例如锁)来强制并发约束。另一种公认的做法是使用go的sync.Map容器。这提供了对我们的地图容器的同步访问,因此可以在多线程方案中安全地使用它。
总结
如何考虑Map的使用,是一件开发过程中必不可少的事情。我们继续学习。