当前位置:网站首页>一道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
}
边栏推荐
- Scan delete folder problems
- Behind every piece of information you collect, you can't live without TA
- Open source SPL enhances mangodb computing
- Differences between seaslog and monolog log systems, installation steps of seaslog [easy to understand]
- leetcode-6127:优质数对的数目
- 【ONNX】pytorch模型导出成ONNX格式:支持多参数与动态输入
- [advanced drawing of single cell] 07. Display of KEGG enrichment results
- [paper reading] unpaired image to image translation using cycle consistent advantageous networks
- Go language go language built-in container
- Leetcode-6130: designing digital container systems
猜你喜欢

Leetcode-155: minimum stack

Embedded development: embedded foundation -- threads and tasks

Leetcode-6127: number of high-quality pairs

Miscellaneous notes -- a hodgepodge

IEC61131 address representation

The database empties the table data and makes the primary key start from 1
![[tensorrt] dynamic batch reasoning](/img/59/42ed0074de7162887bfe2c81891e20.png)
[tensorrt] dynamic batch reasoning

Has baozi ever played in the multi merchant system?

Unity VS—— VS中默认调试为启动而不是附加到Unity调试
![[today in history] July 19: the father of IMAP agreement was born; Project kotlin made a public appearance; New breakthroughs in CT imaging](/img/e9/5751dc435cfbbefc22d84fd9ebbaea.png)
[today in history] July 19: the father of IMAP agreement was born; Project kotlin made a public appearance; New breakthroughs in CT imaging
随机推荐
Golang language quickly get started to comprehensive practical notes (go language, beego framework, high concurrency chat room, crawler)
Basic knowledge of Marine Geology
Niuke-top101-bm38
[technical dry goods] how to ensure the idempotency of the interface?
[tensorrt] trtexec tool to engine
Leetcode customs clearance: hash table six, this is really a little simple
Character function and string function (2)
[matlab] download originality documents based on oil monkey script and MATLAB
day04_ array
Automated testing ----- selenium (I)
【FiddlerTX插件】使用Fiddler抓包腾讯课堂视频下载(抓不到包解决方案)
Vulnhub | dc: 5 | [actual combat]
Huatai Securities account opening process, is it safe to open an account on your mobile phone
[today in history] July 18: Intel was founded; The first photo was posted on the world wide web; EBay spins off PayPal
牛客-TOP101-BM38
Clickhouse notes 02 -- installation test clickvisual
The database empties the table data and makes the primary key start from 1
Increase swap space
Question and answer 47: geeks have an appointment - the current monitoring system construction of CSC
Success factors of software R & D effectiveness measurement