exchange 函数详解


 1 #include 
 2 #include 
 3 #include 
 4 #include 
 5 #include 
 6 #include 
 7 #include 
 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 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 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)

相关