Bibliothèque atomique C ++ - échange

La description

Il remplace atomiquement la valeur de l'objet atomique et obtient la valeur détenue précédemment.

Déclaration

Voici la déclaration pour 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;

Paramètres

  • desired - Il est utilisé pour attribuer la valeur.

  • order - Il est utilisé pour appliquer une contrainte d'ordre mémoire.

Valeur de retour

Il renvoie la valeur de la variable atomique avant l'appel.

Des exceptions

No-noexcept - cette fonction membre ne lève jamais d'exceptions.

Exemple

Dans l'exemple ci-dessous pour 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;
}