How does the lock statement ensure intra processor synchronization?

前端 未结 3 1144
萌比男神i
萌比男神i 2021-02-08 04:55

I have a small test application that executes two threads simultaneously. One increments a static long _value, the other one decrements it. I\'ve ensured with

3条回答
  •  心在旅途
    2021-02-08 05:11

    Cache coherence in this case does not depend on lock. If you use lock statement it ensures that your assembler commands are not mixed. a += b is not an atomic to processor, it looks like:

    • Load data into register from memory
    • Increment data
    • Store data back

    And without lock it may be:

    • Load data into register X from memory
    • Load data into register Y from memory
    • Increment data (in X)
    • Decrement data (in Y)
    • Store data back (from X)
    • Store data back (from Y) // In this case increment is lost.

    But it's not about cache coherence, it's a more high-level feature.

    So, lock does not ensures that the caches are synchronized. Cache synchronization is a processor internal feature which does not depend on code. You can read about it here.

    When one core writes a value to memory and then when the second core try to read that value it won't have the actual copy in its cache unless its cache entry is invalidated so a cache miss occurs. And this cache miss forces cache entry to be updated to actual value.

提交回复
热议问题