【C++编程】exchange 函数详解
https://www.jianshu.com/u/9456fecb5f96
1 #include <algorithm> 2 #include <atomic> 3 #include <cstddef> 4 #include <iostream> 5 #include <thread> 6 #include <vector> 7 #include <mutex> 8 9 int main() 10 { 11 const std::size_t ThreadNumber = 5; 12 const int Sum = 2; 13 std::atomic<int> atom{0}; 14 std::atomic<int> counter{0}; 15 std::mutex flush; 16 17 auto lambda = [&](const int id) 18 { 19 for (int next = 0; next < Sum; ++next) 20 { 21 const int current = atom.exchange(next); 22 counter++; 23 { 24 std::lock_guard<std::mutex> lg(flush); 25 std::cout << '#' << id << " (" << std::this_thread::get_id() 26 << ") wrote " << next << " replacing the old value " << current << '\n'; 27 } 28 } 29 }; 30 31 std::vector<std::thread> v; 32 for (std::size_t i = 0; i < ThreadNumber; ++i) 33 v.emplace_back(lambda, i); 34 35 for (auto &tr : v) 36 tr.join(); 37 38 std::cout << ThreadNumber << " threads adding 0 to " 39 << Sum << " takes total " << counter << " times\n"; 40 }
template< class T, class U = T > T exchange( T& obj, U&& new_value );
template< class T, class U = T > T exchange( T& obj, U&& new_value ); |
(since C++14) |