while (lock != 0) { } lock = 1; critical do work lock = 0;
top: load $R1, lock bne $R1 0 top addi $R1, $R0, 1 store $R1, lock ... store $R0, lock
lock P1 P2 Other Process 1 store $R0, lock 0 load $r1, lock 0 beq $r1, top (not taken) 0 addi $r1, $r0, 1 (enters critical area) 0 store $R1, lock 0 load $R1, lock 0 beq $r1, top (not taken) 1 addi $R1, 1 (enters critical area) 1 store $R1, lock BOTH THREADS IN CRITICAL REGION.
#include <atomic>
atomic<type> varname{init}
varname.fetch_add(value)
for doubles.