In C is “i+=1;” atomic?

来源:互联网 发布:js 元素样式 编辑:程序博客网 时间:2024/06/05 02:08

原文: http://stackoverflow.com/questions/1790204/in-c-is-i-1-atomic/1790234#1790234

=================================================================================================================

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.

=================================================================================================================

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.)

=================================================================================================================

Defined in C, no. In practice, maybe. Write it in assembly.

The standard make no guarantees.

Therefore a portable program would not make the assumption. It's not clear if you mean "required to be atomic", or "happens to be atomic in my C code", and the answer to that second question is that it depends on a lot of things:

  • Not all machines even have an increment memory op. Some need to load and store the value in order to operate on it, so the answer there is "never".

  • On machines that do have an increment memory op, there is no assurance that the compiler will not output a load, increment, and store sequence anyway, or use some other non-atomic instruction.

  • On machines that do have an increment memory operation, it may or may not be atomic with respect to other CPU units.

  • On machines that do have an atomic increment memory op, it may not be specified as part of the architecture, but just a property of a particular edition of the CPU chip, or even just of certain core logic or motherboard designs.

As to "how do I do this atomically", there is generally a way to do this quickly rather than resort to (more expensive) negotiated mutual exclusion. Sometimes this involves special collision-detecting repeatable code sequences. It's best to implement these in an assembly language module, because it's target-specific anyway so there is no portability benefit to the HLL.

Finally, because atomic operations that do not require (expensive) negotiated mutual exclusion are fast and hence useful, and in any case needed for portable code, systems typically have a library, generally written in assembly, that already implements similar functions.

=================================================================================================================