liveBook · Manning

Test-and-set

As explained in C++ Concurrency in Action, Second Edition

`test_and_set()` is a `std::atomic_flag` member function that sets the flag and returns its previous value as one atomic operation.

`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

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Defines the previous-value result and read-modify-write behavior, then demonstrates acquire/release use.
Examples
Demonstrates a spin-lock mutex that loops on test-and-set and clears the flag on unlock.
What you can do after
Apply it via std::atomic_flag to implement a spin-lock mutex with acquire/release ordering.
How it connects
Connects test-and-set to std::atomic_flag, memory ordering, and spin locks.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.