当前位置:网站首页>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
}
边栏推荐
- 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
- Card link
- DDD的Go实战
- Canvas fill gradient
- The database empties the table data and makes the primary key start from 1
- Introduction to MySQL engine and InnoDB logical storage structure
- Unity vs -- the default debugging in VS is to start rather than attach to unity debugging
- leetcode-919:完全二叉树插入器
- 牛客-TOP101-BM38
- Leetcode-79: word search
猜你喜欢

IEC61131 address representation

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

Illustration leetcode - 3. longest substring without repeated characters (difficulty: medium)

基于腾讯地图实现精准定位,实现微信小程序考勤打卡功能

leetcode-6130:设计数字容器系统

Card link

103. (cesium chapter) cesium honeycomb diagram (square)

How to choose a microservice registration center?

Opencv learning Fourier transform experience and line direction Fourier transform code

Canvas 填充渐变
随机推荐
Niuke-top101-bm37
When MySQL resets the root password and modifies the password, an error occurs. The password field does not exist
What's special about Huawei's innovative solutions to consolidate the foundation of ERP for small and medium-sized enterprises?
[technical dry goods] how to ensure the idempotency of the interface?
wokerman 自定义写入日志文件
Niuke-top101-bm38
预处理指令
[paper reading] unpaired image to image translation using cycle consistent advantageous networks
[cloud native] use of Nacos taskmanager task management
[leetcode] 28. Implement strstr ()
The uniapp project starts with an error binding Node is not a valid Win32 Application ultimate solution
leetcode-79:单词搜索
Add startup software items when the win system starts up
Cesium 多边形渐变色纹理(Canvas)
DDD的Go实战
Debugged PEB (beingdebugged, ntglobalflag)
103. (cesium chapter) cesium honeycomb diagram (square)
Character function and string function (2)
seven point two three
Remote—基本原理介绍