Is the “++” operation atomic in C?

2020-07-24 06:33发布

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.

1条回答
叼着烟拽天下
2楼-- · 2020-07-24 06:39

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.

查看更多
登录 后发表回答