SoFunction
Updated on 2025-03-04

Example of method of Golang implementing concurrent reading and writing to map

When using global maps in the case of Golang multi-coroutines, if thread synchronization is not done, panic will occur.

To solve this problem, there are usually two ways:

  • The first is the most common method of using mutex locks or read and write locks;
  • The second method is a more consistent with Golang's characteristics. It starts a single coroutine to read and write maps. When other coroutines need to read and write maps, send a signal to the coroutine through channel.

A simulation program reads or writes an item in the map. The coroutine running in the background blocks the read and write signals and operates on the map. However, when reading, I didn't think about how to return this value.

Later I thought of defining the structure by passing reference. The first parameter is the read and write flag, and the second parameter is the channel of the value after reading or writing successfully, and the defined channel is the channel pointer of the structure.

ps: Verify the efficiency in the future. Simple encapsulation:https:///article/

package main

import (
 "fmt"
 "strconv"
 "time"
)

type value struct {
 id int
 op int
 ret chan int
}
var dic map[int]int
var ch chan *value

func readAndWrite2Map() {
 for {
 select{
 case flag := <- ch:

  if  > 0 {
  ("id: %v, op: %v, ret: %v", , , )
  dic[1] = 
   <- dic[1]
  } else if  == 0 {
  ("id: %v, op: %v, ret: %v", , , dic[1])
   <- dic[1]
  } else {
  return
  }
 }
 }
}


func out(flag, i, val int) {
 if flag == 0 {
 ((i) + "th goroutine read the value is ", val)
 } else {
 ((i)+"th goroutine write to the map ", val)
 }
}

func main() {
 dic = make(map[int]int)
 ch = make(chan *value)
 dic[1] = -1
 go readAndWrite2Map()
 for i := 0; i <= 5; i++ {
 if (i % 2) == 0 {
  go func(i int) {
   var tmp value
   for {
    = 0
   ch <- &tmp
   out(0, i, <-)
   ()
   }
  }(i)

 } else {
  go func(i int) {
   var tmp value
   for {
    = i
   ch <- &tmp
   out(1, i, <-)
   ()

   }
  }(i)
 }
 }
 ( * 60)
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.