2024-07-10 00:18:40 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
// 并发安全版map
|
2024-07-10 00:20:13 +08:00
|
|
|
// 不需要初始化,直接使用即可
|
2024-07-10 00:18:40 +08:00
|
|
|
var sm sync.Map
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
w := sync.WaitGroup{}
|
|
|
|
for i := 0; i < 10; i++ {
|
|
|
|
w.Add(1)
|
|
|
|
go func(n int) {
|
|
|
|
defer w.Done()
|
|
|
|
key := strconv.Itoa(n)
|
|
|
|
sm.Store(key, n) //必须使用sync.Map内置的store方法去设置键值对
|
|
|
|
value, _ := sm.Load(key) //必须使用sync.Map内置的load方法取值
|
|
|
|
fmt.Printf("k:%v,v:%v\n", key, value)
|
|
|
|
}(i)
|
|
|
|
}
|
|
|
|
w.Wait()
|
|
|
|
}
|