Search code examples
c++cstructvariable-assignmentatomic

Is struct assignment atomic in C/C++?


I am writing a program which has one process reading and writing to a shared memory and another process only reading it. In the shared memory there is a struct like this:


struct A{
    int a;
    int b;
    double c;
};

what I expect is to read the struct at once because while I am reading, the other process might be modifying the content of the struct. This can be achieved if the struct assignment is atomic, that is not interrupted. Like this:


struct A r = shared_struct;

So, is struct assignment atomic in C/C++? I tried searching the web but cannot find helpful answers. Can anyone help? Thank you.


Solution

  • No, both C and C++ standard don't guarantee assignment operations to be atomic. You need some implementation-specific stuff for that - either something in the compiler or in the operating system.