COMS W4995 C++ Deep Dive for C Programmers

Index of 2026-1/code/19

Parent directory
atomic.cpp

atomic.cpp

// TODO: lock-free programming

/*
Plan:

1. Rework wallet to use std::atomic instead of std::mutex (compare performance with mutex?)
   Some note about how hardware guarantees atomicty -- through special instructions.. may not always be better
2. is_always_lock_free() check and how builtin types are lock-free. custom
   structures may not always be lock-free -- runtime check for alignment
3. By default using sequentially consistent memory ordering -- prevents any
   reordering, potentially removing opportunity for optimization. in programs,
   could be an index or pointer and multiple threads coordinate access. not only
   provides mutex to that variable, but also guarantees consistent access to other
   data related to that variable accessed across threads. in the face of modern
   cpus reordering instructions, you need to make sure ops before and after
   atomic ops are not reordered. cpp allows specifying memory ordering for atomic ops.
   - relaxed: no ordering constraints, only atomicity guaranteed
4. op++ is fetch_add, takes additional argument. by default strict but try
relaxed memory because there is no other data structures dependent on the atomic
variable.
 but performance is still same on x86 but better on ARM -- explain x86 is
 default fairly strong, but still weaker than cpp default -- doesnt make a difference in this case.
 ARM architecture 
 5. other orderings: acquire/release
- simple example with flag and data
- mutex example with test_and_set
6. summary of orderings



*/