Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C is "i+=1;" atomic? [duplicate]

Tags:

c

atomic

In C, is i+=1; atomic?

like image 933
Crazy Chenz Avatar asked Nov 24 '09 13:11

Crazy Chenz


People also ask

Is int atomic in C?

In practice, you can assume that int is atomic. You can also assume that pointer types are atomic; that is very convenient. Both of these assumptions are true on all of the machines that the GNU C Library supports and on all POSIX systems we know of.

Is ++ atomic in C?

On objects without an atomic type, standard never defines ++ as an atomic operation.

Is increment Atomic C?

The increment-memory machine instruction on an X86 is atomic only if you use it with a LOCK prefix. x++ in C and C++ doesn't have atomic behavior.

What is atomic variable 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.


2 Answers

The C standard does not define whether it is atomic or not.

In practice, you never write code which fails if a given operation is atomic, but you might well write code which fails if it isn't. So assume it isn't.

like image 79
Steve Jessop Avatar answered Sep 23 '22 19:09

Steve Jessop


No.

The only operation guaranteed by the C language standard to be atomic is assigning or retrieving a value to/from a variable of type sig_atomic_t, defined in <signal.h>.

(C99, chapter 7.14 Signal handling.)

like image 40
DevSolar Avatar answered Sep 23 '22 19:09

DevSolar