|
板凳
楼主 |
发表于 2021-8-6 15:48:29
|
只看该作者
- #include <iostream>
- //#include <boost/thread/thread.hpp>
- #include <thread>
- #include <vector>
- //解决1、三个线程共享了资源,把共享去掉即可 比较高效与简单的方法
- //如果可能,必须要用的方法 不使用共享变量就可以了 多定义一下变量即可啊 最后汇总
- // 原则:如果没有必要,线程间不要共享资源
- class Counter{
- public:
- Counter() : m_count(0) {}
- void addCount() {m_count++;}
- int count() const {return m_count;}
- private:
- int m_count;
- };
- int work(int a){
- //do something
- return a + a;
- }
- template <typename Iter>
- void real_work(Counter& c, double& total_value, Iter b, Iter e){
- for(;b!=e;++b){
- total_value += work(*b);
- c.addCount();
- }
- }
- int main(){
- std::cout << "最大并发数=" << std::thread::hardware_concurrency() << std::endl;
- // Counter c1;
- // std::cout << c1.count()<< std::endl;
- // c1.addCount();
- // c1.addCount();
- // std::cout << c1.count()<< std::endl;
- std::vector<int> vec;
- for(int i=0;i<10000000;++i){
- vec.push_back(rand() % 100);
- }
- //没跑一次的时候来计数
- Counter c1;
- double total_value = 0.0f;
- for(auto v : vec){
- total_value += work(v);
- c1.addCount();
- }
- std::cout << "计数器的执行次数=" << c1.count() << "结果=" << total_value << std::endl;
- //开多线程来做同样的工作 三个线程都会去操作的对象:c2和total_value 共享变量
- Counter c2,c3,c4;
- total_value = 0.0f;
- double total_value1 = 0.0f;
- double total_value2 = 0.0f;
- auto iter1 = vec.begin() + (vec.size() / 3);
- auto iter2 = vec.begin() + (vec.size() / 3 * 2);
- //一共三个线程 主线程 子线程t1 子线程t2
- // lambda函数? 知识盲区
- // 引用传进去:c2 total_value
- // 作为值传进去:两个迭代器
- std::thread t1([&c3,&total_value1,iter1,iter2]{
- real_work(c3,total_value1,iter1,iter2);
- });
- auto end = vec.end();
- std::thread t2([&c4,&total_value2,iter2,end]{
- real_work(c4,total_value2,iter2,end);
- });
- //主线程里 做第一区间的
- real_work<std::vector<int>::iterator>(c2,total_value,vec.begin(),iter1);
- // for(auto iter=vec.begin(); iter!=iter1; iter++){
- // total_value += work(*iter);
- // c2.addCount();
- // }
- t1.join();
- t2.join();
- std::cout << "multithread_计数器的执行次数=" << c2.count()+c3.count()+c4.count() << "结果=" << total_value+total_value1+total_value2 << std::endl;
-
- return 0;
- }
复制代码 |
|