Hard
A spinlock using memory_order_relaxed for test_and_set and clear
Both lock() and unlock() below use memory_order_relaxed. Two threads use this spinlock to protect increments of a plain (non-atomic) shared counter. Mutual exclusion on the flag itself (never two threads simultaneously past test_and_set()) is not in question here. Is that enough to make shared++ safe?
main.cpp
class Spinlock {
std::atomic_flag flag = ATOMIC_FLAG_INIT;
public:
void lock() {
while (flag.test_and_set(std::memory_order_relaxed)) {
// spin
}
}
void unlock() {
flag.clear(std::memory_order_relaxed);
}
};
Spinlock lk;
int shared = 0; // plain, non-atomic, protected only by lk (supposedly)
void worker() {
lk.lock();
shared++; // read-modify-write on plain int
lk.unlock();
}
// Thread 1: worker(); Thread 2: worker();43 of 51 in Concurrency