Chapter 2: Q43E (page 173)
Question: Write the MIPS assembly code to implement the following C code:
lock(lk);
shvar=max(shvar.x);
unlock(lk);
Assume that the address of the lk variable is in \(a0, the address of the shvar variable is in \)a1, and the value of variable x is in $a2. Your critical section should not contain any function calls. Use ll/sc instructions to implement the lock() operation and the unlock() operation is simply an ordinary store instruction.
Short Answer
The MIPS assembly code to implement the given C code:
trylk: li $t1,1
ll $t0,0($a0)
bnez $t0,trylk
sc $t1, 0($a0)
beqz $t1, trylk
lw $t2, 0($a1)
slt $t3,$t2,$a2
bnez $t3, skip
sw $a2, 0(a1)
skip:sw $0, 0($a0)