std::atomic_exchange, std::atomic_exchange_explicit

Header: <atomic>

1,2) Atomically replaces the value pointed to by obj with the value of desired and returns the value obj held previously, as if by obj->exchange(desired).

# Declarations

template< class T >
T atomic_exchange( std::atomic<T>* obj,
typename std::atomic<T>::value_type desired ) noexcept;

(since C++11)

template< class T >
T atomic_exchange( volatile std::atomic<T>* obj,
typename std::atomic<T>::value_type desired ) noexcept;

(since C++11)

template< class T >
T atomic_exchange_explicit( std::atomic<T>* obj,
typename std::atomic<T>::value_type desired,
std::memory_order order ) noexcept;

(since C++11)

template< class T >
T atomic_exchange_explicit( volatile std::atomic<T>* obj,
typename std::atomic<T>::value_type desired,
std::memory_order order ) noexcept;

(since C++11)

# Parameters

# Return value

The value held previously by the atomic object pointed to by obj.

# Example

#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
 
std::atomic<bool> lock(false); // holds true when locked
                               // holds false when unlocked
 
int new_line{1}; // the access is synchronized via atomic lock variable
 
void f(int n)
{
    for (int cnt = 0; cnt < 100; ++cnt)
    {
        while (std::atomic_exchange_explicit(&lock, true, std::memory_order_acquire))
            ; // spin until acquired
        std::cout << n << (new_line++ % 80 ? "" : "\n");
        std::atomic_store_explicit(&lock, false, std::memory_order_release);
    }
}
 
int main()
{
    std::vector<std::thread> v;
    for (int n = 0; n < 8; ++n)
        v.emplace_back(f, n);
    for (auto& t : v)
        t.join();
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
P0558R1C++11exact type match was required becauseT was deduced from multiple argumentsT is only deducedfrom obj

# See also