std::atomic is new feature introduced by c++11 but I can't find much tutorial on how to use it correctly. So are the following practice common and efficient?
One practice I used is we have a buffer and I want to CAS on some bytes, so what I did was:
uint8_t *buf = .... auto ptr = reinterpret_cast<std::atomic<uint8_t>*>(&buf[index]); uint8_t oldValue, newValue; do { oldValue = ptr->load(); // Do some computation and calculate the newValue; newValue = f(oldValue); } while (!ptr->compare_exchange_strong(oldValue, newValue));
So my questions are:
EDIT: if those questions are processor/architecture dependent, then what's the conclusion for x86/x64 processors?
std::atomic. Each instantiation and full specialization of the std::atomic template defines an atomic type. If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined (see memory model for details on data races).
Atomic variables are much slower than non-atomic ones.
Yes, it would be threadsafe. Assuming of course there are no bugs in the std::atomic implementation - but it's not usually hard to get right. This is exactly what std::atomic is meant to do.
std::atomic is not copyable or movable because its copy constructor is deleted and no move constructor is defined.
The reinterpret_cast
will yield undefined behaviour. Your variable is either a std::atomic<uint8_t>
or a plain uint8_t
; you cannot cast between them. The size and alignment requirements may be different, for example. e.g. some platforms only provide atomic operations on words, so std::atomic<uint8_t>
will use a full machine word where plain uint8_t
can just use a byte. Non-atomic operations may also be optimized in all sorts of ways, including being significantly reordered with surrounding operations, and combined with other operations on adjacent memory locations where that can improve performance.
This does mean that if you want atomic operations on some data then you have to know that in advance, and create suitable std::atomic<>
objects rather than just allocating a generic buffer. Of course, you could allocate a buffer and then use placement new
to initialize your atomic variable in that buffer, but you'd have to ensure the size and alignment were correct, and you wouldn't be able to use non-atomic operations on that object.
If you really don't care about ordering constraints on your atomic object then use memory_order_relaxed
on what would otherwise be the non-atomic operations. However, be aware that this is highly specialized, and requires great care. For example, writes to distinct variables may be read by other threads in a different order than they were written, and different threads may read the values in different orders to each other, even within the same execution of the program.
If CAS is slower for a byte than a word, you may be better off using std::atomic<unsigned>
, but this will have a space penalty, and you certainly can't just use std::atomic<unsigned>
to access a sequence of raw bytes --- all operations on that data must be through the same std::atomic<unsigned>
object. You are generally better off writing code that does what you need and letting the compiler figure out the best way to do that.
For x86/x64, with a std::atomic<unsigned>
variable a
, a.load(std::memory_order_acquire)
and a.store(new_value,std::memory_order_release)
are no more expensive than loads and stores to non-atomic variables as far as the actual instructions go, but they do limit the compiler optimizations. If you use the default std::memory_order_seq_cst
then one or both of these operations will incur the synchronization cost of a LOCK
ed instruction or a fence (my implementation puts the price on the store, but other implementations may choose differently). However, memory_order_seq_cst
operations are easier to reason about due to the "single total ordering" constraint they impose.
In many cases it is just as fast, and a lot less error-prone, to use locks rather than atomic operations. If the overhead of a mutex lock is significant due to contention then you might need to rethink your data access patterns --- cache ping pong may well hit you with atomics anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With