Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atomicity of the simple assignment operator

C11 Standard says that for atomic types (_Atomic), prefix and postfix ++ and -- operations are atomic (6.5.2.4.,p2), as are compound assignments: op= (6.5.16.2,p3).

I haven't found anything written about a simple assignment =. Is it also atomic?

Let's says E1, E2 are int, but only E1 is defined with the specifier _Atomic. My assumption is that this:

E1 = E2;

is equivalent to:

atomic_store( &E1 , E2 );

It my assumption correct?

like image 585
2501 Avatar asked Jan 19 '16 19:01

2501


People also ask

What is atomicity in C?

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 assignment operations atomic?

Yes. Assignment of premitive types and reference types are atomic. Read the ECMA C# language specification.

Are assignments atomic in C?

In C and C++, every operation is presumed non-atomic unless otherwise specified by the compiler or hardware vendor – even plain 32-bit integer assignment. The language standards have nothing to say about atomicity in this case.

Is assignment atomic in Java?

First of all, reference assignment is atomic because the specification says so. Besides that, there is no obstacle for JVM implementors to fulfill this constraint, as 64 Bit references are usually only used on 64 Bit architectures, where atomic 64 Bit assignment comes for free.


1 Answers

Following the example in this Dr Dobbs article, simple assignment of atomic variables in C11 is atomic.

The C11 standard (ISO/IEC 9899:2011), section 6.2.6.1/9 reads:

Loads and stores of objects with atomic types are done with memory_order_seq_cst semantics.

In addition to being atomic, operations performed with memory_order_seq_cst semantics have a single ordering observed by all threads (aka sequentially-consistent ordering).

Without the _Atomic type qualifier, it is possible for an assignment to be non-atomic. Assigning a 64 bit value (e.g. a long long) on a 32 bit machine requires two CPU cycles. If another thread reads the value between those two cycles they'll get 4 bytes of the old value and 4 bytes of the new value.

like image 180
Isaac Turner Avatar answered Oct 29 '22 18:10

Isaac Turner