This is a creation in Article, where the information may have evolved or changed.
One, map concurrency and read-write problems
Fatal error:concurrent map Read and map write error if map is read and written simultaneously by multiple co-processes
The following code is easy to appear map concurrency read and write problems
Func main () {c := make (map[string]int) go func () {//Open a co-process write map for j := 0; j < 1000000; j++ { c[fmt. Sprintf ("%d", j)] = j } } () go func () { //Open a co-process read map for j := 0; j < 1000000; j++ { fmt. Println (c[fmt. Sprintf ("%d", j)]) } } () time. Sleep (time. SECOND*20)}
Fatal Error:concurrent Map writes errors occur with multiple concurrent writes
The following code is prone to the problem of map concurrency write
package mainimport ("fmt""time")func main() {c := make(map[string]int)for i := 0; i < 100; i++ {go func() { //开100个协程并发写mapfor j := 0; j < 1000000; j++ {c[fmt.Sprintf("%d", j)] = j}}()}time.Sleep(time.Second * 20) //让执行main函数的主协成等待20s,不然不会执行上面的并发操作}
Second, the cause of the problem
Because the map is a reference type, so even if the function is called, the parameter copy still points to the mapping m, so many goroutine concurrently write the same mapping m, write too many threads of the students know that, for shared variables, resources, concurrent read and write will produce competition, so the sharing of resources is compromised
Third, the solution
1, lock
(1) Universal lock
type Demo struct { Data map[string]string Lock sync.Mutex}func (d Demo) Get(k string) string{ d.Lock.Lock() defer d.Lock.UnLock() return d.Data[k]}func (d Demo) Set(k,v string) { d.Lock.Lock() defer d.Lock.UnLock() d.Data[k]=v}
(2) Read/write lock
type Demo struct { Data map[string]string Lock sync.RwMutex}func (d Demo) Get(k string) string{ d.Lock.RLock() defer d.Lock.RUnlock() return d.Data[k]}func (d Demo) Set(k,v string) { d.Lock.Lock() defer d.Lock.UnLock() d.Data[k]=v}
2, the use of channel serialization processing