Do spin locks always require a memory barrier? Is spinning on a memory barrier expensive?

后端 未结 3 1203
日久生厌
日久生厌 2020-12-14 12:11

I wrote some lock-free code that works fine with local reads, under most conditions.

Does local spinning on a memory read necessarily imply I have to ALWAYS insert a

3条回答
  •  忘掉有多难
    2020-12-14 12:54

    The "xchg reg,[mem]" instruction will signal its lock intention over the LOCK pin of the core. This signal weaves its way past other cores and caches down to the bus-mastering buses (PCI variants etc) which will finish what they are doing and eventually the LOCKA (acknowledge) pin will signal the CPU that the xchg may complete. Then the LOCK signal is shut off. This sequence can take a long time (hundreds of CPU cycles or more) to complete. Afterwards the appropriate cache lines of the other cores will have been invalidated and you will have a known state, i e one that has ben synchronized between the cores.

    The xchg instruction is all that is neccessary to implement an atomic lock. If the lock itself is successful you have access to the resource that you have defined the lock to control access to. Such a resource could be a memory area, a file, a device, a function or what have you. Still, it is always up to the programmer to write code that uses this resource when it's been locked and doesn't when it hasn't. Typically the code sequence following a successful lock should be made as short as possible such that other code will be hindered as little as possible from acquiring access to the resource.

    Keep in mind that if the lock wasn't successful you need to try again by issuing a new xchg.

    "Lock free" is an appealing concept but it requires the elimination of shared resources. If your application has two or more cores simultaneously reading from and writing to a common memory address "lock free" is not an option.

提交回复
热议问题