spinlock
HOW
WHO
-
HW synchronization primitive
-
동작:
- lock 안 풀리면 계속 while loop 돌면서 busy waiting
-
특징:
- context switch 없음
- CPU 계속 점유
EX
struct spinlock {
uint locked; // Is the lock held?
// For debugging:
char *name; // Name of lock.
struct cpu *cpu; // The cpu holding the lock.
};// Acquire the lock.
// Loops (spins) until the lock is acquired.
void
acquire(struct spinlock * lk) {
push_off(); // disable interrupts to avoid deadlock.
if (holding(lk))
panic("acquire");
// On RISC-V, sync_lock_test_and_set turns into an atomic swap:
// a5 = 1
// s1 = &lk->locked
// amoswap.w.aq a5, a5, (s1)
while (__sync_lock_test_and_set( &lk->locked, 1) != 0);
__sync_synchronize();
// Record info about lock acquisition for holding() and debugging.
lk -> cpu = mycpu();
}
// Release the lock.
void
release(struct spinlock * lk) {
if (!holding(lk))
panic("release");
lk -> cpu = 0;
__sync_synchronize();
// Release the lock, equivalent to lk->locked = 0.
// This code doesn't use a C assignment, since the C standard
// implies that an assignment might be implemented with
// multiple store instructions.
// On RISC-V, sync_lock_release turns into an atomic swap:
// s1 = &lk->locked
// amoswap.w zero, zero, (s1)
__sync_lock_release( &lk->locked);
pop_off();
}WHEN & WHERE
- “빠르게 끝날 critical section”에 적합