`std::atomic_flag::test_and_set()` atomically sets the flag and returns its previous value. A clear flag returns false; a set flag returns true. It is a read-modify-write operation, and its default memory order is `std::memory_order_seq_cst`. section 5.2.1 section 5.2.2
Listing 5.1. Implementation of a spinlock mutex using std::atomic_flag
class spinlock_mutex
{
std::atomic_flag flag;
public:
spinlock_mutex():
flag(ATOMIC_FLAG_INIT)
{}
void lock()
{
while(flag.test_and_set(std::memory_order_acquire));
}
void unlock()
{
flag.clear(std::memory_order_release);
}
};
The spin-lock loop repeats while test-and-set reports that the flag was already set. A release clear lets a later acquisition proceed. section 5.2.2
