Atomic Compare and Swap

Hard Assembly Synchronization Asked at ARM
Solve this problem

Implement an atomic compare-and-swap on ARM using the exclusive load and store instructions, the primitive every lock-free structure is built on.

Constraints

  • Signature: int cas(int *ptr, int expected, int desired) returning 1 on success.
  • Use LDREX and STREX.
  • Must clear the exclusive monitor on the failure path.
  • Retry only on a store-exclusive failure, not on a value mismatch.
  • No memory barriers required for the core operation itself.
  • AAPCS register usage.
Starter codeAssembly
1.global cas2cas:3    @ r0 = ptr, r1 = expected, r2 = desired4    @ TODO5    bx lr