SoFunction
Updated on 2025-03-05

Go uses to solve the problem of concurrent operation of maps

Preface

In Golang, map is not concurrency-safe, and it was introduced since 1.9. The introduction of ? ? It does solve the concurrency security problem of map, but it does not implement the len() function. If you want to calculate the length, it is a little troublesome and you need to use the Range function.

There is a problem with map concurrent operation

func main() {
 demo := make(map[int]int)

 go func() {
  for j := 0; j < 1000; j++ {
   demo[j] = j
  }
 }()

 go func() {
  for j := 0; j < 1000; j++ {
   (demo[j])
  }
 }()

 ( * 1)
}

Execute output:

fatal error: concurrent map read and map write

Solve concurrent operation problems

func main() {
 demo := {}

 go func() {
  for j := 0; j < 1000; j++ {
   (j, j)
  }
 }()

 go func() {
  for j := 0; j < 1000; j++ {
   ((j))
  }
 }()

 ( * 1)
}

Execute output:
<nil> false
1 true

...

999 true

Calculate map length

func main() {
 demo := make(map[int]int)

 for j := 0; j < 1000; j++ {
  demo[j] = j
 }

 ("len of demo:", len(demo))
}

Execute output:
len of demo: 1000

Calculate length

func main() {
 demo := {}
 
 for j := 0; j < 1000; j++ {
  (j, j)
 }

 lens := 0
 (func(key, value interface{}) bool {
  lens++
  return true
 })

 ("len of demo:", lens)
}

Execute output:
len of demo: 1000

summary

  • Load load key data
  • Store updates or adds key data
  • Delete key data
  • Range traversal data
  • LoadOrStore will return if key data exists, otherwise set
  • LoadAndDelete If key data exists, delete it

This is the article about using Go to solve the concurrent operation problems of maps. For more related content on Go to solve the concurrent operation of maps, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!