1、代码
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
var sMap sync.Map
var b = false
func readMap(sInfo string, sMap *sync.Map) {
for {
if b {
break
}
time.Sleep(time.Second)
xV, _ := sMap.Load("x")
fmt.Printf("%v sMap['x']=%v\n", sInfo, xV)
}
}
func writeMap(sInfo string, sMap *sync.Map) {
for {
if b {
break
}
time.Sleep(time.Second)
sMap.Store("x", rand.Int31())
xV, _ := sMap.Load("x")
fmt.Printf("%v sMap['x']=%v\n", sInfo, xV)
}
}
func main() {
sMap.Store("x", 0)
go readMap("reading<1>", &sMap)
go readMap("reading<2>", &sMap)
go writeMap("writing ", &sMap)
time.Sleep(time.Second * 3)
b = true
//等待两秒,等待所有线程执行结束
time.Sleep(time.Second * 2)
sMap.Range(func(key, value interface{}) bool {
fmt.Println("删除前遍历", key, value)
return true
})
sMap.Delete("x")
sMap.Range(func(key, value interface{}) bool {
fmt.Println("删除后遍历", key, value)
return true
})
}
2、输出
![](https://i-blog.csdnimg.cn/blog_migrate/bf7dc41cbe2c496275313a2dd521ce1d.png)