编译器优化
减少不必要的代码或指令以达到优化;
CPU优化
关系密切的操作提前执行,而不是顺序执行;
优化带来的问题
莫名其妙的bug,且不容易复现;
编译器指令优化
volatile
修饰的变量,和它有关的代码都不会优化;- 但是默认会优化
cpu
缓存更新
处理器的cpu
发送队列和接受队列并不会实时处理; 而是触发机制;
cpu
提供了对应的指令进行强制处理; w,r barrier.
, 这样就可以强制刷新发送队列或接受队列;
避免编译重排
__asm__ __volatile__("":::"memory")
- 但是默认会重排
- https://coffeebeforearch.github.io/2020/11/21/compiler-memory-ordering.html
cpu
的重排
- 相似相近的代码提前执行; 默认重排
- 查看对应处理器文档,提供的相关汇编指令;
- http://gavinchou.github.io/summary/c++/memory-ordering/
参考
https://developer.arm.com/documentation/den0042/a/Memory-Ordering/Memory-barriers
https://stackoverflow.com/questions/22106843/gccs-reordering-of-read-write-instructions
https://en.wikipedia.org/wiki/Memory_barrier
https://stackoverflow.com/questions/39062100/how-does-cpu-reorder-instructions