【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)
posted @   苏格拉底的落泪  阅读(276)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
点击右上角即可分享
微信分享提示