EasyManua.ls Logo

Freescale Semiconductor PowerPC e500 Core - Notes; A.1.1.5 Test and Set

Default Icon
548 pages
Print Icon
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
PowerPC e500 Core Family Reference Manual, Rev. 1
A-4 Freescale Semiconductor
Programming Examples
A.1.1.5 Test and Set
This version of the test and set primitive atomically loads a word from memory, sets the word in
memory to a nonzero value if the value loaded is zero, and sets the EQ bit of CR Field 0 to indicate
whether the value loaded is zero.
In this example it is assumed that the address of the word to be tested is in GPR3, the new value
(nonzero) is in GPR4, and the old value is returned in GPR5.
loop: lwarx r5,0,r3 #load and reserve
cmpwi r5,0 #done if word
bc 4,2,done # not equal to 0
stwcx. r4,0,r3 #try to store non-0
bc 4,2,loop #loop if lost reservation
done:
A.1.1.6 Compare and Swap
The compare and swap primitive atomically compares a value in a register with a word in memory,
if they are equal stores the value from a second register into the word in memory, if they are
unequal loads the word from memory into the first register, and sets CR0[EQ] to indicate the result
of the comparison.
In this example it is assumed that the address of the word to be tested is in GPR3, the comparand
is in GPR4 and the old value is returned there, and the new value is in GPR5.
loop: lwarx r6,0,r3 #load and reserve
cmpw r4,r6 #1st 2 operands equal?
bc 4,2,exit #skip if not
stwcx. r5,0,r3 #store new value if still reserved
bc 4,2,loop #loop if lost reservation
exit: or r4,r6,r6 #return value from memory
A.1.1.7 Notes
1. The semantics given for compare and swap above are based on those of the IBM
System/370 compare and swap instruction. Other architectures may define a compare and
swap instruction differently.
2. Compare and swap is shown primarily for pedagogical reasons. It is useful on machines
that lack the better synchronization facilities provided by lwarx and stwcx.. A major
weakness of a System/370-style compare and swap instruction is that, although the
instruction itself is atomic, it checks only that the old and current values of the word being
tested are equal, with the result that programs that use such a compare and swap to control
a shared resource can err if the word has been modified and the old value subsequently
restored. The sequence shown above has the same weakness.

Table of Contents

Related product manuals