sync.once 确保执行一次 sync.map并发安全版map finished

main
Your Name 2024-07-10 00:18:40 +08:00
parent 3c356f488a
commit 237c06768b
3 changed files with 100 additions and 0 deletions

32
sync/sync.map.go Normal file
View File

@ -0,0 +1,32 @@
package main
import (
"fmt"
"strconv"
"sync"
)
// GO内置的map不是并发安全的
var m = make(map[string]int)
func get(key string) int {
return m[key]
}
func set(key string, value int) {
m[key] = value
}
func main() {
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go func(n int) {
key := strconv.Itoa(n)
set(key, n)
fmt.Printf("k=:%v,v:=%v\n", key, get(key))
wg.Done()
}(i)
}
wg.Wait()
}

26
sync/sync.map_example.go Normal file
View File

@ -0,0 +1,26 @@
package main
import (
"fmt"
"strconv"
"sync"
)
// 并发安全版map
//无需初始化
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()
}

42
sync/sync.once.go Normal file
View File

@ -0,0 +1,42 @@
package main
import "sync"
//某些操作只需要在高并发场景中做一次,例如加载配置文件
//这种场景下用到sync.once
var waitGroup sync.WaitGroup
var once sync.Once
func send(ch1 chan<- int) {
defer waitGroup.Done()
for i := 0; i < 100; i++ {
ch1 <- i
}
close(ch1)
}
func getV(ch1 <-chan int, ch2 chan<- int) {
defer waitGroup.Done()
for {
x, ok := <-ch1
if !ok {
break
}
ch2 <- x * x
}
once.Do(func() { close(ch2) })
}
func main() {
a := make(chan int, 100)
b := make(chan int, 100)
waitGroup.Add(3)
go send(a)
go getV(a, b)
go getV(a, b)
waitGroup.Wait()
for ret := range b {
println(ret)
}
}