- The C Standard Library
- The C Standard Library
- The C++ Standard Library
- C++ Library - Home
- C++ Library - <fstream>
- C++ Library - <iomanip>
- C++ Library - <ios>
- C++ Library - <iosfwd>
- C++ Library - <iostream>
- C++ Library - <istream>
- C++ Library - <ostream>
- C++ Library - <sstream>
- C++ Library - <streambuf>
- C++ Library - <atomic>
- C++ Library - <complex>
- C++ Library - <exception>
- C++ Library - <functional>
- C++ Library - <limits>
- C++ Library - <locale>
- C++ Library - <memory>
- C++ Library - <new>
- C++ Library - <numeric>
- C++ Library - <regex>
- C++ Library - <stdexcept>
- C++ Library - <string>
- C++ Library - <thread>
- C++ Library - <tuple>
- C++ Library - <typeinfo>
- C++ Library - <utility>
- C++ Library - <valarray>
- The C++ STL Library
- C++ Library - <array>
- C++ Library - <bitset>
- C++ Library - <deque>
- C++ Library - <forward_list>
- C++ Library - <list>
- C++ Library - <map>
- C++ Library - <queue>
- C++ Library - <set>
- C++ Library - <stack>
- C++ Library - <unordered_map>
- C++ Library - <unordered_set>
- C++ Library - <vector>
- C++ Library - <algorithm>
- C++ Library - <iterator>
- C++ Programming Resources
- C++ Programming Tutorial
- C++ Useful Resources
- C++ Discussion
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
To Continue Learning Please Login
Login with Google