深入學習c++--多線程編程(一)


1. 簡介

2. 線程使用

2.1 demo

#include <iostream>
#include <thread>
#include <future>
using namespace std; 

void helloworld()
{
    cout << "hello world \n"; 
}

int main()
{
    
    //開啟一個線程 
    std::thread t(helloworld);
    std::cout << "hello world main thread\n";
    
    //線程的終結
    t.join(); 
    
    return 0;
}

2.2 一個簡單的應用

  • 查看當前線程id: this_thread::get_id()
  • 比較單線程和多線程工作的效率(如果工作不太消耗時間,多線程反而比單線程更耗時間)
#include <iostream>
#include <thread>
#include <chrono>
#include <future>
#include <cmath> 
#include <vector>
#include <cstdlib>
using namespace std; 

double caculate(int v)
{
    if (v <= 0) {
        return v;
    }
    //假設這個計算很慢 
    this_thread::sleep_for(chrono::milliseconds(10));
    return sqrt((v * v + sqrt((v - 5) * (v + 2.5)) / 2.0) / v); 
}

template<typename Iter, typename Fun>
double visitRange(thread::id id, Iter iterBegin, Iter iterEnd, Fun func)
{
    auto curId = this_thread::get_id();
    if (id == this_thread::get_id()) {
        cout << curId << " hello main thread\n";
    }
    else {
        cout << curId << " hello work thread\n";
    } 
    double v = 0;
    for (auto iter = iterBegin; iter != iterEnd; ++iter) {
        v += func(*iter);
    }
    return v;
}

int main()
{
    auto mainThreadId = std::this_thread::get_id();
    //開啟一個線程 
    std::vector<double> v;
    for (int i = 0; i < 1000; i++) 
    {
        v.push_back(rand());
    } 
    cout << v.size() << endl;
     double value = 0.0;  
    auto st = clock();        
    for (auto & info : v)
    {
        value += caculate(info);        
    }
    auto ed = clock();
    cout << "single thread: " << value << " " << ed - st << "time" << endl;
    
    
    //下面用多線程來進行 
    
    auto iterMid = v.begin() + (v.size() / 2);     // 指向整個vector一半部分
    //計算后半部分
    double anotherv = 0.0;
    auto iterEnd = v.end();
    st = clock();    
    
    std::thread s([&anotherv, mainThreadId, iterMid, iterEnd]() {           // lambda 
        anotherv = visitRange(mainThreadId, iterMid, iterEnd, caculate);
        
    });
    // 計算前半部分 
    auto halfv = visitRange(mainThreadId, v.begin(), iterMid, caculate);

    //關閉線程 
    s.join(); 
    
    ed = clock();
    cout << "multi thread: " << (halfv + anotherv) << " " << ed - st << "time" << endl;
    
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM