Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 497
RockU Avatar asked Mar 31 '11 10:03

RockU


People also ask

Are assignments atomic in C?

What is an atomic operation in C? Neither of them are, although it is quite rare for the assignment to not be atomic. You have to document the core and compiler to get a useful answer.

Is assignment an atomic operation?

Yes. Assignment of premitive types and reference types are atomic. Read the ECMA C# language specification. Actually, that's not entirely true, only assignments to reference types, bool, char, byte, sbyte, short, ushort, uint, int and float are atomic.

What are atomic in C?

Remarks. Atomics as part of the C language are an optional feature that is available since C11. Their purpose is to ensure race-free access to variables that are shared between different threads. Without atomic qualification, the state of a shared variable would be undefined if two threads access it concurrently.

Are pointers Atomic?

The main risk is that only ptr is atomic. But this does not apply to the values pointed to. To be noted that especially pointers bring further synchronisation risk when you reassign the atomic pointer to a non atomic pointer.


2 Answers

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.

like image 118
sharptooth Avatar answered Nov 02 '22 21:11

sharptooth


C and C++ support atomic types in their current standards.

C++11 introduced support for atomic types. Likewise C11 introduced atomics.

like image 23
David Heffernan Avatar answered Nov 02 '22 19:11

David Heffernan