Skip to content

Commit 2a96bbf

Browse files
committed
add note of cppcon
1 parent f141ee0 commit 2a96bbf

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

_code/CppCon/2017/cpp_atomics.md

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,4 +86,50 @@ problem: if weak CAS correctly returns x == old+x, why would it fail?
8686

8787
Lock is not a real mutex but some form of exclusive access implemented in hardware.
8888

89-
Read is faster than write.
89+
Double-checked locking pattern is back.
90+
91+
## Usage
92+
93+
Atomic variable is an index or pointer to non-atomic memory.
94+
95+
Atomic variables as gateways to memory access.
96+
97+
Atomic are used to exclusive access to memory or to reveal memory to other threads.
98+
99+
## Memory Barriers
100+
101+
Memory barriers control how changes to memory made by one cpu become visible to other CPUs.
102+
103+
Memory barriers are closely related to memory order.
104+
105+
`std::memory_order_relaxed`: no barriers
106+
107+
`std::memory_order_acquire`: nothing after load can move in front of it, anything before can move after.
108+
109+
`std::memory_order_release`: is reverse.
110+
111+
acquire release order often used together. One thread prepare date then releases and the other acquires atomic variable.
112+
113+
`std::memory_order_acq_rel`: combines acquire and release
114+
115+
`std::memory_order_seq_cst`: no need for same atomic variable.
116+
117+
CAS have two memory orders.
118+
119+
Default memory order is `std::memory_order_seq_cst`, the strongest order. But it is expensive.
120+
121+
Lock free code is hard to write and hard to read. clarity matters.
122+
123+
Sequential consistency makes your program easier to understand and often has no performance penalty.
124+
125+
Lock-based program can only memory_order_acquire and memory_order_release.
126+
127+
## When to use std::atomic in your c++ code
128+
129+
Data structures that are difficult or expensive to implement with lock.
130+
131+
When drawbacks of locks are important.(deadlocks, priority conflicts, latency problems)
132+
133+
When concurrent synchronization can be achieved by the cheapest atomic operations.
134+
135+
ref: talks on RCU

0 commit comments

Comments
 (0)