Alex Rivera | Logout

Is struct assignment atomic in C/C++?

Asked 2011-03-31T10:46:51.687
21

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.

Edit
Report

1 Answer

18

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.

answered 2011-03-31T10:48:17.710

Your Answer