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:
- The above code uses ugly reinterpret_cast and is this the correct way to retrieve the atomic pointer that reference to the location &buf[index]?
- Is the CAS on a single byte significantly slower than CAS on a machine word, so that I should avoid using it? My code will look more complicated if I change it to load a word, extract the byte, compute and set the byte in the new value, and do CAS. This makes the code more complicated and I also need to deal with address alignment myself.
EDIT: if those questions are processor/architecture dependent, then what's the conclusion for x86/x64 processors?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…