当前位置:网站首页>N++ is not reliable
N++ is not reliable
2022-07-04 13:09:00 【Brother Xiaokun】
Xiao Ming went to the interview again today , I was asked another strange interview question :
n := 0
for i := 0; i < 1000000; i++ {
go func() {
n++
}()
}
fmt.Println(n)
It's time for you to think , What results are output ?
Xiao Ming thought for a long time , Gave his answer : I do not know! , Then the interviewer told him : You passed .
Isn't it a little crazy , you 're right , The result of this code is that I don't know , The result of each execution is different , Look at it all cpu How to dispatch .
Let me tell you something slowly .
One 、 The original prototype
According to the interview code , Roll back a little , Look at this code :
n := 0
for i := 0; i < 1000000; i++ {
func() {
n++
}()
}
fmt.Println(n)
Let's get rid of Xie Cheng , Now the result is not very good to know , Yes, it's the number of cycles 1000000.
Two 、 The pit inside
Let's go back to the interview code , There are actually two pits :
The first pit : He didn't wait for it , So it is likely to sweep away , The main program is over before it has been cycled several times , Even quit without doing a cycle .
But in the interview , Generally, this pit is not mentioned , This is not the point of the interview , Of course, you can also mention .
The second pit is the focus of the interview :
Without considering the early exit of the main thread , After joining the process ,n++ The result of is not accurate .
Why? ?
because n++ Not atomic , He wants to finish n++ He needs to do three steps :
Get the value from memory perform +1 operation Assign back
Because it's not atomic , So it is likely that other line layers are also taking values when you take values , Also calculating , The last assignment will be overwritten , Thus, random and unpredictable results appear .
3、 ... and 、 How to guarantee the result ?
because n++ It's not atomic , If we want him to become an atom , There are two common operations :
1、 Lock
First of all, we want to ensure that he can finish the cycle , I need to add one wait:
wg := sync.WaitGroup{}
n := 0
for i := 0; i < 1000000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
n++ // It's not atomic 1、 Read from memory 2、n++ 3、 assignment
}()
}
wg.Wait()
fmt.Println(n)
In this way, he can finish the execution , Then add our thread layer lock :
wg := sync.WaitGroup{}
locker := sync.Mutex{}
n := 0
for i := 0; i < 1000000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
// lock
defer locker.Unlock()
locker.Lock()
n++ // It's not atomic 1、 Read from memory 2、n++ 3、 assignment
}()
}
wg.Wait()
fmt.Println(n)
The result of this execution , Each time is the number of executions .
2、 Use atomic
We occasionally use atomic Package to handle such operations , But there are certain limitations , The data types he supports are limited .
Go straight to the code :
var n int32 = 0
for i := 0; i < 1000000; i++ {
func() {
atomic.AddInt32(&n, 1) // Atomic manipulation
}()
}
fmt.Println(n)
Here we put n Turned into int32 type , Such operation result can also guarantee the number of cycles .
边栏推荐
- Fly tutorial 02 advanced functions of elevatedbutton (tutorial includes source code) (tutorial includes source code)
- 6 分钟看完 BGP 协议。
- 众昂矿业:为保障萤石足量供应,开源节流势在必行
- Solution: how to delete the information of Jack in two tables with delete in one statement in Oracle
- go-zero微服务实战系列(九、极致优化秒杀性能)
- I want to talk about yesterday
- MySQL three-level distribution agent relationship storage
- Definition of cognition
- WPF双滑块控件以及强制捕获鼠标事件焦点
- 诸神黄昏时代的对比学习
猜你喜欢
Building intelligent gray-scale data system from 0 to 1: Taking vivo game center as an example
[leetcode] 96 and 95 (how to calculate all legal BST)
A treasure open source software, cross platform terminal artifact tabby
Jetson TX2 configures common libraries such as tensorflow and pytoch
面试官:Redis 过期删除策略和内存淘汰策略有什么区别?
高效!用虚拟用户搭建FTP工作环境
Play Sanzi chess easily
How real-time cloud interaction helps the development of education industry
0x15 string
Talk about the design and implementation logic of payment process
随机推荐
[data clustering] section 3 of Chapter 4: DBSCAN performance analysis, advantages and disadvantages, and parameter selection methods
游戏启动后提示安装HMS Core,点击取消,未再次提示安装HMS Core(初始化失败返回907135003)
老掉牙的 synchronized 锁优化,一次给你讲清楚!
Is there an elegant way to remove nulls while transforming a Collection using Guava?
轻松玩转三子棋
Efficient! Build FTP working environment with virtual users
Building intelligent gray-scale data system from 0 to 1: Taking vivo game center as an example
AI 绘画极简教程
runc hang 导致 Kubernetes 节点 NotReady
Transformer principle and code elaboration (tensorflow)
Jetson TX2配置Tensorflow、Pytorch等常用库
模块化笔记软件综合评测:Craft、Notion、FlowUs
Introduction to the button control elevatedbutton of the fleet tutorial (the tutorial includes the source code)
使用 NSProxy 实现消息转发
阿里云有奖体验:用PolarDB-X搭建一个高可用系统
Kivy tutorial 08 countdown app implements timer call (tutorial includes source code)
Jetson TX2 configures common libraries such as tensorflow and pytoch
使用 NSProxy 实现消息转发
C语言:围圈报号排序问题
用fail2ban阻止密码尝试攻