computer-architecture concurrency memory-models
Definition
Load-Reserved Store-Conditional
Load-reserved/store-conditional is an atomic synchronisation primitive consisting of two operations on the same memory location:
- Load-reserved loads the value and reserves the address.
- Store-conditional stores a new value only if the reservation is still valid.
If another thread accesses the same location between the two operations, the reservation is lost and the store-conditional fails.
Semantics
Reservation
lr.wreturns the current value at the address and marks that address as reserved.
sc.wsucceeds only if the reservation is still valid; it writes the new value and returns success, otherwise it writes nothing and returns failure.
Indivisible update by retry
LR/SC does not make the whole read-modify-write a single instruction. Instead, it detects interference and forces the caller to retry until the update succeeds.
Relation to AMO
Different atomic style
LR/SC is an alternative to atomic read-modify-write instructions such as
amoswap.w. AMO performs the update in one instruction; LR/SC splits the update into a reservation phase and a conditional store.
Examples
Spinlock with LR/SC
A lock can be implemented by repeatedly reading the lock variable and attempting to store
1only if it is still0:li a2, 1 .LBB0_1: lr.w a1, (a0) bnez a1, .LBB0_1 sc.w a3, a2, (a0) bnez a3, .LBB0_1 retThe lock is acquired only when
sc.wsucceeds.