当前位置:网站首页>一道golang中关于map的并发读写的面试题
一道golang中关于map的并发读写的面试题
2022-07-25 20:48:00 【youngqqcn】
下面的代码有什么问题?
package main
import (
"fmt"
"sync"
)
// 下面的代码有什么问题?
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()
}
请思考,答案和解析在下文
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
答案,会panic
fatal error: concurrent map read and map write
为什么?
// map是并发读写不安全的。map属于引用类型,
// 并发读写时多个协程见是通过指针访问同一个地址,即访问共享变量,此时同时读写资源存在竞争关系。会报错误信息:
// fatal error: concurrent map read and map write
// sync.Mutex 和 sync.RWMutex
//
// Mutex 为互斥锁,Lock() 加锁,Unlock() 解锁
//
// RWMutex 为读写锁,
// 写锁会阻止其他 goroutine(无论读和写)进来,整个锁由该 goroutine 独占
// 适用于读多写少的场景
如何改写,才能解决并发的问题?
第1种:给读也加上互斥锁
func (ua *UserAges) Get(name string) int {
ua.Lock()
defer ua.Unlock()
if age, ok := ua.ages[name]; ok {
return age
}
return -1
}
第2种,用 sync.RWMutex 改写,适合“多读少写”并发场景
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
}
边栏推荐
- Introduction to MySQL engine and InnoDB logical storage structure
- [MSA] a brief description of the moveit Configuration Assistant chain in planning groups
- How to choose a microservice registration center?
- Wokerman custom write log file
- leetcode-6125:相等行列对
- Question and answer 47: geeks have an appointment - the current monitoring system construction of CSC
- Leetcode-919: complete binary tree inserter
- 牛客-TOP101-BM38
- How to use buffer queue to realize high concurrent order business (glory Collection Edition)
- Temperature and humidity environment monitoring system based on stm32
猜你喜欢

Mobile web layout method

leetcode-79:单词搜索

Today's sleep quality record 75 points

【FiddlerTX插件】使用Fiddler抓包腾讯课堂视频下载(抓不到包解决方案)

Leetcode-919: complete binary tree inserter

Leetcode-6127: number of high-quality pairs

leetcode-6127:优质数对的数目

The international summit osdi included Taobao system papers for the first time, and end cloud collaborative intelligence was recommended by the keynote speech of the conference

IEC61131 address representation
![MySQL date [plus sign / +] condition filtering problem](/img/86/aed048e27b3e0b0baa919204bc067c.png)
MySQL date [plus sign / +] condition filtering problem
随机推荐
Miscellaneous notes -- a hodgepodge
Introduction to several scenarios involving programming operation of Excel in SAP implementation project
Detailed explanation of document operation
[advanced drawing of single cell] 07. Display of KEGG enrichment results
Remote monitoring solution of intelligent electronic boundary stake Nature Reserve
Basic knowledge of Marine Geology
牛客-TOP101-BM38
Key network protocols in tcp/ip four layer model
day04_ array
Use Navicat to connect to MySQL database through SSH channel (pro test is feasible)
Go language go language built-in container
Today's sleep quality record 75 points
Question and answer 47: geeks have an appointment - the current monitoring system construction of CSC
[MSA] a brief description of the moveit Configuration Assistant chain in planning groups
In June 2021, the interview suffered a Waterloo. Is it so convoluted now
Scan delete folder problems
Wokerman custom write log file
seven point two three
[workplace rules] it workplace rules | poor performance
matlab----EEGLab查看脑电信号