Bibliothèque atomique C ++ - échange

La description

Il remplace automatiquement la valeur de l'objet atomique par un argument non atomique et renvoie l'ancienne valeur de l'atome.

Déclaration

Voici la déclaration pour std :: atomic_exchange.

template< class T >
T atomic_exchange( std::atomic<T>* obj, T desr );

C ++ 11

template< class T >
T atomic_exchange( volatile std::atomic<T>* obj, T desr );

Paramètres

  • obj - Il est utilisé en pointeur sur l'objet atomique à modifier.

  • desr - Il est utilisé pour stocker la valeur dans l'objet atomique.

  • order - Il est utilisé pour synchroniser l'ordre de la mémoire pour cette opération.

Valeur de retour

Il renvoie la valeur précédemment détenue par l'objet atomique pointé par obj.

Des exceptions

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

Exemple

Dans l'exemple ci-dessous pour std :: atomic_exchange.

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

std::atomic<bool> lock(false);

void f(int n) {
   for (int cnt = 0; cnt < 100; ++cnt) {
      while(std::atomic_exchange_explicit(&lock, true, std::memory_order_acquire))
             ;
        std::cout << "Output from thread " << n << '\n';
        std::atomic_store_explicit(&lock, false, std::memory_order_release);
   }
}
int main() {
   std::vector<std::thread> v;
   for (int n = 0; n < 10; ++n) {
      v.emplace_back(f, n);
   }
   for (auto& t : v) {
      t.join();
   }
}

La sortie devrait être comme ça -

Output from thread 0
Output from thread 1
Output from thread 0
Output from thread 1
Output from thread 0
Output from thread 1
Output from thread 0
Output from thread 1
.....................