当前位置:网站首页>An interview question about concurrent reading and writing of map in golang
An interview question about concurrent reading and writing of map in golang
2022-07-25 20:53:00 【youngqqcn】
What's wrong with the code below ?
package main
import (
"fmt"
"sync"
)
// What's wrong with the code below ?
type UserAges struct {
ages map[string]int
sync.Mutex
}
func (ua *UserAges) Add(name string, age int) {
ua.Lock()
defer ua.Unlock()
ua.ages[name] = age
}
func (ua *UserAges) Get(name string) int {
if age, ok := ua.ages[name]; ok {
return age
}
return -1
}
// test
func main() {
ua := &UserAges{
ages: make(map[string]int, 0)}
wg := &sync.WaitGroup{
}
wg.Add(10 + 4)
// write
for gid := 10000; gid < 10010; gid++ {
go func(gid int, u *UserAges) {
for i := 0; i < 100000; i++ {
name := fmt.Sprintf("gid%d-%d", gid, i)
u.Add(name, i)
}
wg.Done()
}(gid, ua)
}
// read
for gid := 10000; gid < 10004; gid++ {
go func(gid int, u *UserAges) {
for i := 0; i < 100000; i++ {
name := fmt.Sprintf("gid%d-%d", gid, i)
_ = u.Get(name)
}
wg.Done()
}(gid, ua)
}
wg.Wait()
}
Please think about it. , The answer and analysis are in the following
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
answer , Meeting panic
fatal error: concurrent map read and map write
Why? ?
// map It is not safe to read and write concurrently .map It's a reference type ,
// When reading and writing concurrently, multiple processes can access the same address through pointers , That is, access to shared variables , At this time, there is a competitive relationship between reading and writing resources . Error messages will be reported :
// fatal error: concurrent map read and map write
// sync.Mutex and sync.RWMutex
//
// Mutex Is mutex ,Lock() Lock ,Unlock() Unlock
//
// RWMutex Lock for read and write ,
// Writing locks will prevent other goroutine( Whether reading or writing ) Come in , The whole lock consists of goroutine Monopoly
// It is suitable for reading more and writing less
How to rewrite , To solve the problem of concurrency ?
The first 1 Kind of : Add mutexes to reads
func (ua *UserAges) Get(name string) int {
ua.Lock()
defer ua.Unlock()
if age, ok := ua.ages[name]; ok {
return age
}
return -1
}
The first 2 Kind of , use sync.RWMutex rewrite , fit “ Read more and write less ” Concurrent scenarios
type UserAges struct {
ages map[string]int
sync.RWMutex
}
func (ua *UserAges) Get(name string) int {
ua.Lock()
defer ua.Unlock()
if age, ok := ua.ages[name]; ok {
return age
}
return -1
}
边栏推荐
- Differences between seaslog and monolog log systems, installation steps of seaslog [easy to understand]
- ROS_ Rqt toolbox
- Detailed explanation of document operation
- Key network protocols in tcp/ip four layer model
- 【FiddlerTX插件】使用Fiddler抓包腾讯课堂视频下载(抓不到包解决方案)
- Temperature and humidity environment monitoring system based on stm32
- Remote - actual combat
- 基于腾讯地图实现精准定位,实现微信小程序考勤打卡功能
- Chapter VI modified specification (SPEC) class
- Remote—实战
猜你喜欢

IEC61131 address representation

Kubernetes advanced part learning notes

Opencv learning Fourier transform experience and line direction Fourier transform code

Canvas 填充渐变

leetcode-79:单词搜索

Unity VS—— VS中默认调试为启动而不是附加到Unity调试

Chinese son-in-law OTA Ono became the first Asian president of the University of Michigan, with an annual salary of more than 6.5 million!

Force deduction ----- calculate the money of the force deduction bank

Cesium 多边形渐变色纹理(Canvas)

leetcode-919:完全二叉树插入器
随机推荐
一道golang中关于接口和实现的面试题
Unity vs -- the default debugging in VS is to start rather than attach to unity debugging
Leetcode customs clearance: hash table six, this is really a little simple
The uniapp project starts with an error binding Node is not a valid Win32 Application ultimate solution
How to realize reliable transmission with UDP?
leetcode-114:二叉树展开为链表
[advanced drawing of single cell] 07. Display of KEGG enrichment results
103. (cesium chapter) cesium honeycomb diagram (square)
7.23
[FAQ] access the HMS core push service, and the server sends messages. Cause analysis and solutions of common error codes
【TensorRT】动态batch进行推理
How to obtain the subordinate / annotation information of KEGG channel
结构体,枚举类型与联合体
"Chain" connects infinite possibilities: digital asset chain, wonderful coming soon!
【网络教程】IPtables官方教程--学习笔记2
【FiddlerTX插件】使用Fiddler抓包腾讯课堂视频下载(抓不到包解决方案)
Opencv learning Fourier transform experience and line direction Fourier transform code
If the order is not paid for 30 minutes, it will be automatically cancelled. How to achieve this? (Collection Edition)
leetcode-146:LRU 缓存
[fiddlertx plug-in] use Fiddler to capture the package Tencent classroom video download (unable to capture the package solution)