Medium
A hand-rolled spinlock built on std::atomic_flag
SpinLock is hand-implemented using std::atomic_flag's test_and_set()/clear() interface. Four threads each run the loop shown, incrementing a shared counter 100,000 times under the spinlock. What is the most accurate statement about this code and about std::atomic_flag in general?
main.cpp
class SpinLock {
std::atomic_flag flag = ATOMIC_FLAG_INIT;
public:
void lock() {
while (flag.test_and_set(std::memory_order_acquire)) {
// busy-wait
}
}
void unlock() {
flag.clear(std::memory_order_release);
}
};
SpinLock sl;
long counter = 0;
void worker() {
for (int i = 0; i < 100000; ++i) {
sl.lock();
++counter;
sl.unlock();
}
}
// 4 threads each run worker(), then join; main prints counter36 of 51 in Concurrency