C++ Atomic Library - exchange



Description

It atomically replaces the value of the atomic object and obtains the value held previously.

Declaration

Following is the declaration for std::atomic::exchange.

T exchange( T desired, std::memory_order order = std::memory_order_seq_cst );

C++11

T exchange( T desired, std::memory_order order = std::memory_order_seq_cst ) volatile;

Parameters

  • desired − It is used to assign the value.

  • order − It is used to enforce memory order constraint.

Return Value

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

Exceptions

No-noexcept − this member function never throws exceptions.

Example

In below example for std::atomic::exchange.

#include <iostream>
#include <atomic>
#include <thread>
#include <vector>

std::atomic<bool> ready (false);
std::atomic<bool> winner (false);

void count1m (int id) {
   while (!ready) {}
   for (int i=0; i<1000000; ++i) {}
   if (!winner.exchange(true)) { std::cout << "thread #" << id << " won!\n"; }
};

int main () {
   std::vector<std::thread> threads;
   std::cout << "spawning 10 threads that count to 1 million...\n";
   for (int i=1; i<=10; ++i) threads.push_back(std::thread(count1m,i));
   ready = true;
   for (auto& th : threads) th.join();

   return 0;
}
atomic.htm
Advertisements