Namespaces
Variants

std:: atomic_flag

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
atomic_flag
(C++11)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
Definido en el encabezado <atomic>
class atomic_flag ;
(desde C++11)

std::atomic_flag es un tipo booleano atómico. A diferencia de todas las especializaciones de std::atomic , se garantiza que está libre de bloqueos. A diferencia de std:: atomic < bool > , std::atomic_flag no proporciona operaciones de carga o almacenamiento.

Funciones miembro

construye un atomic_flag
(función miembro pública)
[deleted]
el operador de asignación (eliminado)
(función miembro pública)
establece atómicamente el flag a false
(función miembro pública)
establece atómicamente el flag a true y obtiene su valor anterior
(función miembro pública)
(C++20)
devuelve atómicamente el valor del flag
(función miembro pública)
(C++20)
bloquea el hilo hasta que sea notificado y el valor atómico cambie
(función miembro pública)
(C++20)
notifica al menos un hilo esperando en el objeto atómico
(función miembro pública)
(C++20)
notifica todos los hilos bloqueados esperando en el objeto atómico
(función miembro pública)

Ejemplo

Una demostración de mutex de spinlock puede implementarse en el espacio de usuario usando un atomic_flag . Tenga en cuenta que los mutexes de spinlock son extremadamente dudosos en la práctica.

#include <atomic>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
class mutex
{
    std::atomic_flag m_{};
  public:
    void lock() noexcept
    {
        while (m_.test_and_set(std::memory_order_acquire))
#if defined(__cpp_lib_atomic_wait) && __cpp_lib_atomic_wait >= 201907L
            // Since C++20, locks can be acquired only after notification in the unlock,
            // avoiding any unnecessary spinning.
            // Note that even though wait guarantees it returns only after the value has
            // changed, the lock is acquired after the next condition check.
            m_.wait(true, std::memory_order_relaxed)
#endif
                ;
    }
    bool try_lock() noexcept
    {
        return !m_.test_and_set(std::memory_order_acquire);
    }
    void unlock() noexcept
    {
        m_.clear(std::memory_order_release);
#if defined(__cpp_lib_atomic_wait) && __cpp_lib_atomic_wait >= 201907L
        m_.notify_one();
#endif
    }
};
static mutex m;
static int out{};
void f(std::size_t n)
{
    for (std::size_t cnt{}; cnt < 40; ++cnt)
    {
        std::lock_guard lock{m};
        std::cout << n << ((++out % 40) == 0 ? '\n' : ' ');
    }
}
int main()
{
    std::vector<std::thread> v;
    for (std::size_t n{}; n < 10; ++n)
        v.emplace_back(f, n);
    for (auto &t : v)
        t.join();
}

Salida posible:

0 1 1 2 0 1 3 2 3 2 0 1 2 3 2 3 0 1 3 2 0 1 2 3 2 3 0 3 2 3 2 3 2 3 1 2 3 0 1 3
2 3 2 0 1 2 3 0 1 2 3 2 0 1 2 3 0 1 2 3 2 3 2 3 2 0 1 2 3 2 3 0 1 3 2 3 0 2 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 3 2 0 2 3 2 3 2 3 2 3 2 3 0 3
2 3 0 3 0 3 2 3 0 3 2 3 2 3 0 2 3 0 3 2 0 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9

Véase también

establece atómicamente la bandera a true y devuelve su valor anterior
(función)
establece atómicamente el valor de la bandera a false
(función)
bloquea el hilo hasta que sea notificado y la bandera cambie
(función)
notifica a un hilo bloqueado en atomic_flag_wait
(función)
notifica a todos los hilos bloqueados en atomic_flag_wait
(función)
inicializa un std::atomic_flag a false
(macro constante)
Documentación de C para atomic_flag