Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the "++" operation atomic in C?

I am trying to determine whether or not a statement like:

++value;   //assuming "value" is a **global** variable

is an atomic operation.

I need to know if this calculation is capable of being interrupted by an Interrupt Service Routine that writes to the same global variable.

like image 765
shakoldo44 Avatar asked Oct 27 '25 03:10

shakoldo44


1 Answers

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

C11 defines atomic types in stdatomic.h. If you have an object with an atomic type, a postfix and prefix operators ++ will define an atomic operation as: read-modify-write operation with memory_order_seq_cst memory order semantics.

You can also use atomic_fetch_add() if you want an atomic increment.

like image 132
2501 Avatar answered Oct 29 '25 07:10

2501



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!