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

后端 未结 12 2095
天命终不由人
天命终不由人 2020-12-28 12:58

In C, is i+=1; atomic?

12条回答
  •  伪装坚强ぢ
    2020-12-28 13:29

    The answer to your question depends on whether i is a local, static, or global variable. If i is a static or global variable, then no, the statement i += 1 is not atomic. If, however, i is a local variable, then the statement is atomic for modern operating systems running on the x86 architecture and probably other architectures as well. @Dan Cristoloveanu was on the right track for the local variable case, but there is also more that can be said.

    (In what follows, I assume a modern operating system with protection on an x86 architecture with threading entirely implemented with task switching.)

    Given that this is C code, the syntax i += 1 implies that i is some kind of integer variable, the value of which, if it is a local variable, is stored in either a register such as %eax or in the stack. Handling the easy case first, if the value of i is stored in a register, say %eax, then the C compiler will most likely translate the statement to something like:

    addl    $1, %eax
    

    which of course is atomic because no other process/thread should be able to modify the running thread's %eax register, and the thread itself cannot modify %eax again until this instruction completes.

    If the value of i is stored in the stack, then this means that there is a memory fetch, increment, and commit. Something like:

    movl    -16(%esp), %eax
    addl    $1, %eax
    movl    %eax, -16(%esp)  # this is the commit. It may actually come later if `i += 1` is part of a series of calculations involving `i`.
    

    Normally this series of operations is not atomic. However, on a modern operating system, processes/threads should not be able to modify another thread's stack, so these operations do complete without other processes being able to interfere. Thus, the statement i += 1 is atomic in this case as well.

提交回复
热议问题