Example of a method that implements concurrent reads and writes to map
- 2020-07-21 08:23:33
- OfStack
When using global map in the case of Golang multiple coroutines, panic can occur if thread synchronization is not done.
To solve this problem, there are usually two ways:
The first is the most common method of using a mutex or read-write lock. The second method is more in line with the features of Golang. A single coroutine is started to read and write map. When other coroutines need to read and write map, a signal can be sent to this coroutine through channel.
A simulation program was written to read or write an item in map. The background 1 direct line coroutine blocked the read/write signal and operated on map, but did not have a good idea how to return this value during the read operation.
The first parameter is the read/write flag, and the second parameter is the channel of the value after the read/write success. In the definition of channel, the pointer to the structure is passed.
ps: Verify the efficiency under 1 later. Under the simple encapsulates the 1: https: / / www ofstack. com article / 157620. htm
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 flag.op > 0 {
log.Printf("id: %v, op: %v, ret: %v", flag.id, flag.op, flag.op)
dic[1] = flag.op
flag.ret <- dic[1]
} else if flag.op == 0 {
log.Printf("id: %v, op: %v, ret: %v", flag.id, flag.op, dic[1])
flag.ret <- dic[1]
} else {
return
}
}
}
}
func out(flag, i, val int) {
if flag == 0 {
fmt.Println(strconv.Itoa(i) + "th goroutine read the value is ", val)
} else {
fmt.Println(strconv.Itoa(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 {
tmp.op = 0
ch <- &tmp
out(0, i, <-tmp.ret)
time.Sleep(time.Millisecond)
}
}(i)
} else {
go func(i int) {
var tmp value
for {
tmp.op = i
ch <- &tmp
out(1, i, <-tmp.ret)
time.Sleep(time.Millisecond)
}
}(i)
}
}
time.Sleep(time.Second * 60)
}