Golang the objects that should be noted in the map or slice operation in multiple go routine.

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Because Golang map and list slices are reference types and are not thread-safe, there is a "map read and map write" Panic error when reading and writing in multiple go routine.

Some types of objects, there will be similar set methods to write data, or get methods to return a map:

Func (this *object) Set (name, Val) {this. Lock () defer this. Unlock () This.m[name] = Val}func (this *object) Get () map[string]string {this. Lock () defer this. Unlock () return THIS.M}

  

If a map is fetched in multiple go routine through the Get () method of the object, and is written using the set () method in the other go routine, it is possible that the panic error of "map read and map write" is caused.

The reason is that the map obtained by the Get method and the map of the set method operation are the same map, which generates an error if the read-write thread operates the 2 maps at the same time.

So the Get method is best to return to the map in this way:

Func (this *object) Get () map[string]string {this    . Lock ()    defer this. Unlock ()    newm: = Make (map[string]string)    for k, V: = range this.m {        Newm[k] = v    }    return NEWM}

So each get gets the map, actually is a new map, you can not consider the problem of reading and writing at the same time.

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.