C++ Atomic::exchange() function



The C++ std::atomic::exchange() function is used to automatically replace the value of an atomic object with a new value and return the old value. This function is essential in multithreading contexts where you need to ensure that the read-write modification operation on a variable is done atomically, preventing data races.

Syntax

Following is the syntax for std::atomic::exchange() function.

T exchange (T val, memory_order sync = memory_order_seq_cst) volatile noexcept;
T exchange (T val, memory_order sync = memory_order_seq_cst) noexcept;

Parameters

  • val − It indicates the value to copy to the contained object.
  • sync It indicates the synchronization mode for the operation.

Return Value

It returns the value of the atomic variable before the call.

Exceptions

This member function never throws exceptions.

Example

In the following example, we are going to consider the basic usage of exchange() function.

#include <iostream>
#include <atomic>
int main()
{
    std::atomic<int> a(10);
    int x = a.exchange(20);
    std::cout << "Old value: " << x << std::endl;
    std::cout << "New value: " << a.load() << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

Old value: 10
New value: 20

Example

Consider the following example, where we are going to perform the atomic exchange using the pointers.

#include <iostream>
#include <atomic>
int main()
{
    char a = 'A', b = 'B';
    std::atomic<char*> x(&a);
    char* y = x.exchange(&b);
    std::cout << "Old pointer value: " << *y << std::endl;
    std::cout << "New pointer value: " << *x << std::endl;
    return 0;
}

Output

Following is the output of the above code −

Old pointer value: A
New pointer value: B

Example

In the following example, we are going to perform the atomic exchange in a multithreaded context.

#include <iostream>
#include <atomic>
#include <thread>
std::atomic<int> x(11);
void a()
{
    int y = x.exchange(22);
    std::cout << "Old value: " << y << std::endl;
}
int main()
{
    std::thread t(a);
    t.join();
    std::cout << "New value: " << x << std::endl;
    return 0;
}

Output

If we run the above code it will generate the following output −

Old value: 11
New value: 22
atomic.htm
Advertisements