I have been reading an article about Lockless Programming in MSDN. It says :
On all modern processors, you can
assume that reads and writes of
naturally aligned native types are atomic. As long as the memory bus is
at least as wide as the type being
read or written, the CPU reads and
writes these types in a single bus
transaction, making it impossible for
other threads to see them in a
half-completed state.
And it gives some examples:
// This write is not atomic because it is not natively aligned.
DWORD* pData = (DWORD*)(pChar + 1);
*pData = 0;
// This is not atomic because it is three separate operations.
++g_globalCounter;
// This write is atomic.
g_alignedGlobal = 0;
// This read is atomic.
DWORD local = g_alignedGlobal;
I read lots of answers and comments saying, nothing is guaranteed to be atomic in C++ and it is not even mentioned in standarts, in SO and now I am a bit confused. Am I misinterpreting the article? Or does the article writer talk about things that are non-standart and specific to MSVC++ compiler?
So according to the article the below assignments must be atomic, right?
struct Data
{
char ID;
char pad1[3];
short Number;
char pad2[2];
char Name[5];
char pad3[3];
int Number2;
double Value;
} DataVal;
DataVal.ID = 0;
DataVal.Number = 1000;
DataVal.Number2 = 0xFFFFFF;
DataVal.Value = 1.2;
If it is true, does replacing Name[5]
and pad3[3]
with std::string Name;
make any difference in memory-alignment ? Will the assignments to Number2
and Value
variables be still atomic?
Can someone please explain?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…