C++ References
目录
- atomic Weapons: The C++ Memory Model and Modern Hardware https://herbsutter.com/2013/02/11/atomic-weapons-the-c-memory-model-and-modern-hardware/
- acquire and release https://preshing.com/20120913/acquire-and-release-semantics/
- fedor g pikus c++ atomics from basic to advanced what they do really do https://www.youtube.com/watch?v=ZQFzMfHIxng
1 Out of order
1.1 Compile Optimization
- Compiler assumes in a single thread and do optimize;
Compiler assumes code is right;
#include <stdio.h> #include <stdlib.h> #include <string.h> struct data { char s[10]; int x; int y; int z; }; int main(int argc, char *argv[]) { struct data d; memset(&d, 0xfc, sizeof(d)); d.z = 0; unsigned int n = strlen(d.s); if (n > 10) n = 10; printf("n = %d\n", n); return 0; }
Compile above code with gcc -O3 opt1.c, the result is 20;
- Dekker's and Peterson's Algorithms
1.2 SC for Data-Race-Free programs(SC-DRF)
- SC: Sequential Consistency
1.3 Acquire and release
- Acquire means "after is after"; Acquire之后的所有指令不会早于这条指令开始执行;尤其是读指令不会;
- Release means "before is before"; Release之前的所有指令都已经执行完毕,尤其是写指令的结果已经全局可见;
- X86 provides ld.acq(acquire.load) and st.rel(Release store)
1.4 cxx consistency
- memory_order_relaxed: 用于Load或Store,操作是原子的,但没有顺序保证,可乱序执行;
- memory_order_release: 用于store,表示Release语义;
- memory_order_acquire: 用于load,表示acquire语义;
- memory_order_acq_rel: 用于load或store,对store表示release语义,对load表示acquire;
- memory_order_seq_cst: 用于load或store,表示SC语义;
- memory_order_consume: 用于load,表示consume语义;
1.5 singleton error
MyClass *p = nullptr; MyClass* get_instance() { if (nullptr == p) { mutex_lock(); if (nullptr == p) { p = new MyClass; } mutex.unlock(); } return p; } // Splits: // p = new MyClass equal to: p = malloc(sizeof(MyClass)); p = new(p) MyClass; // May out of order, and caller get a uninitialized object
Correct Method: https://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/
atomic<MyClass> *p = nullptr; MyClass* get_instance() { if (nullptr == p) { mutex_lock(); if (nullptr == p) { p = new MyClass; } mutex.unlock(); } return p; }
Singleton best one:
MyClass* get_instance() { static MyClass instance; return instance; }
Singleton free see Modern c++ Design: Generic Programming and Design patterns Applied.
- Performance compare non-atomic-store: 1 atomic-increase: 15 atomic-store: 30 compare-exchange-strong: 45