The Cortex®-M4 instruction set includes pairs of synchronization primitives which provide a nonblocking mechanism that a thread or process can use to obtain exclusive access to a memory location. Software can use these primitives to perform an ensured read-modify-write memory update sequence or for a semaphore mechanism.
A pair of synchronization primitives consists of:
- A load-exclusive instruction, to read the value of a memory location and request exclusive access to that location.
- A store-exclusive instruction, to try to write to the same memory location and return a status bit to a register. If this status bit is clear, it indicates that the thread or process gained exclusive access to the memory and the write succeeds; if this status bit is set, it indicates that the thread or process did not gain exclusive access to the memory and no write was performed.
The pairs of load-exclusive and store-exclusive instructions are:
- The word instructions LDREX and STREX
- The halfword instructions LDREXH and STREXH
- The byte instructions LDREXB and STREXB
Software must use a load-exclusive instruction with the corresponding store-exclusive instruction. To perform an exclusive read-modify-write of a memory location, software must:
- Use a load-exclusive instruction to read the value of the location.
- Modify the value, as required.
- Use a store-exclusive instruction to try to write the new value back to the memory location.
- Test the returned status bit. If the status bit is clear, the read-modify-write completed successfully. If the status bit is set, no write was performed, which indicates that the value returned at Step 1 might be out of date. The software must retry the entire read-modify-write sequence.
Software can use the synchronization primitives to implement a semaphore as follows:
- Use a load-exclusive instruction to read from the semaphore address, to check whether the semaphore is free.
- If the semaphore is free, use a store-exclusive instruction to write the claim value to the semaphore address.
- If the returned status bit from Step 2 indicates that the store-exclusive succeeded, then the software has claimed the semaphore. However, if the store-exclusive failed, another process might have claimed the semaphore after the software performed Step 1.
The Cortex®-M4 includes an exclusive access monitor that tags the fact that the processor has executed a load-exclusive instruction. The processor removes its exclusive access tag if one of the following occurs:
- It executes a CLREX instruction.
- It executes a store-exclusive instruction, regardless of whether the write succeeds.
- An exception occurs, which means the processor can resolve semaphore conflicts between different threads.
For more information about the synchronization primitive instructions, see the Cortex®-M4 instruction set chapter in the Arm® Cortex®-M4 Devices Generic User Guide (ARM DUI 0553A).