Map concurrency and read-write problem in Golang and its solving method

Source: Internet
Author: User
Tags sprintf
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

Related Article

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.