liveBook · Manning

Clear()

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

`clear()` is a `std::atomic_flag` member function that sets the flag to the clear state.

`clear()` sets a `std::atomic_flag` to its clear state. It is a store operation: its default memory order is `memory_order_seq_cst`, and it cannot use `memory_order_acquire` or `memory_order_acq_rel`. section 5.2.1 section 5.2.2

A spin-lock mutex uses `clear(std::memory_order_release)` in `unlock()` to clear its flag with release semantics. 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 mutex implementation shows `clear()` in the unlock operation. section 5.2.2

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

How deep it goes
Defines clearing as a store, gives its default ordering, and rules out acquire and acquire-release semantics.
Examples
Uses `clear(std::memory_order_release)` in a spin-lock mutex’s `unlock()` function.
What you can do after
Apply `std::atomic_flag::clear()` to release a spin-lock mutex.
How it connects
Connects `std::atomic_flag` to memory ordering and spin-lock mutexes.

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.