As is known to all, the Golang map is non-coprocessor safe (go1.6 version, after go1.6 read security), and the need for concurrent read and write map should be very common. Examples are as follows:
package mainimport "fmt"func main() { a := make(map[int]bool, 0) for i:=0;i<100;i++{ go func() { for i := 0; i < 20000; i++ { a[i] = false fmt.Printf("%v %v\n",i,a[i]) } }() }}
Operation Error:
Fatal Error:concurrent Map writes
Prior to version 1.9, the official solution was to encapsulate a struct with a sync lock. For example:
package mainimport ( "fmt" "sync")type SafeMap struct{ sync.RWMutex data map[int]int}func main() { a := SafeMap{data: make(map[int]int)} for i:=0;i<100;i++{ go func() { for j := 0; j < 20000; j++ { a.Lock() a.data[j] = i fmt.Printf("%v %v\n", i, j) a.Unlock() } }() }}
After the 1.9 release, the sync pack introduced sync. MAP, performance compared to the previous solution has a relatively large increase:
Package Main import ("FMT" "Sync") func main () {A: = new (sync. MAP) WG: = new (sync. WAITGROUP) WG. ADD (+) for i:=0;i<100;i++{go func () {for j: = 0; J < A.store (i, J)} WG. Done ()} ()} WG. Wait () A.range (func (Key, Value interface{}) bool {FMT. Printf ("%v%v\n", key, Value) return true})}