Home  >  Article  >  Backend Development  >  Why is golang map not concurrent?

Why is golang map not concurrent?

(*-*)浩
(*-*)浩Original
2019-12-14 11:40:593727browse

Why is golang map not concurrent?

The map data type is found in many languages. It is a hash table in the form of key and value, so that key and value can be mapped one by one for fast search, addition, deletion, etc. operate. The Go language is no exception, providing the map data structure type.

# (Recommended learning: Go )

Golang, the map is a reference type, such as Like pointer slicing, it points to nil after being declared with the following code. This is also explained in the golang official documentation, so never use it directly after declaring it. You may often make the following mistakes at first:

var m map[string]string
m["result"] = "result"

The first line of code above does not initialize the map. , but writing to it is a reference to a null pointer, which will cause a painc.

So, you must remember to use the make function to allocate memory and initialize it:

m := make(map[string]string)
m["result"] = "result"

map in golang is not concurrency safe

I often use map, and it feels good to use it, but suddenly one day the traffic increases, and the program hangs up without knowing it. I don’t know what happened, but it was working fine before.

So some good habits should be developed at the beginning, such as assertion checking, concurrency safety considerations, etc.

Even though map is easy to use, you have to be careful. Perhaps many people still don't know that Golang's built-in map is not actually concurrency-safe.

Maybe you can try sync.Map

The sync.Map in golang is concurrency safe. In fact, it is a custom name of golang in the sync package. Map structure. The structure prototype is as follows:

type Map struct {
   mu Mutex
   read atomic.Value // readOnly
   dirty map[interface{}]*entry
   misses int
}

The above is the detailed content of Why is golang map not concurrent?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn