Author: Chen Jinjian
personal blog: HTTPS: //jian1098.github.io
CSDN blog: https: //blog.csdn.net/c_jian
Jane book: https: //www.jianshu.com/u/8ba9ac5706b6
Contact: jian1098 @qq.com
Run the following program will report an errorfatal error: concurrent map writes
package main
import "time"
var m = make(map[int]int)
func main() {
for i := 0; i < 10; i++ {
go func(n int) {
m[n]=n
}(i)
}
time.Sleep(time.Duration(2)*time.Second)
}
The reason is that the map is a reference type. Concurrent writes to the map will cause competition when high concurrency. An error will be reported regardless of whether the same key is the same or not, and concurrent reads to the map will not cause problems.
Solution one
Replace map with sync.Map
package main
import (
"fmt"
"sync"
"time"
)
var m sync.Map
func main() {
for i := 0; i < 10; i++ {
go func(n int) {
m.Store("a",n) //写入
}(i)
}
time.Sleep(time.Duration(2)*time.Second)
fmt.Println(m.Load("a")) //读取
//遍历
m.Range(func(k, v interface{
}) bool {
fmt.Println( k, v)
return true
})
}
Solution two
Lock
package main
import (
"fmt"
"sync"
"time"
)
var m = make(map[int]int)
var lock sync.Mutex
func main() {
for i := 0; i < 10; i++ {
go func(n int) {
lock.Lock() //加锁,加锁期间其他协程会进入阻塞状态直到解锁
time.Sleep(time.Duration(2)*time.Second)
fmt.Println(n,"在执行")
m[n]=n
lock.Unlock() //解锁
}(i)
}
time.Sleep(time.Duration(20)*time.Second)
}