Medium
A spinlock that calls sched_yield() between attempts
Two SCHED_OTHER threads are pinned to isolated cores 2 and 3. Nothing else is runnable on either core. The thread on core 2 holds the lock below for about 50 µs. During that time, what is the waiting thread on core 3 actually doing?
yield_lock.cpp
#include <atomic>
#include <sched.h>
std::atomic<bool> locked{false};
void lock() {
while (locked.exchange(true, std::memory_order_acquire)) {
sched_yield(); // "let someone else run"
}
}
void unlock() { locked.store(false, std::memory_order_release); }52 of 53 in Operating Systems