Solution for concurrent Environment application map

Source: Internet
Author: User

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})}  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.