C++多线程初步

理论上,系统有多少个逻辑内核,就可以开多少个线程。
这里通过两个例子,完成对线程的初步理解。

例 1:图片读取

    auto read_image_1 = std::async(&BevDetSingle::readCvImage, this, camera_front_left , std::ref(raw_data_buffer->raw_data[0]), resize_size);
    auto read_image_2 = std::async(&BevDetSingle::readCvImage, this, camera_front      , std::ref(raw_data_buffer->raw_data[1]), resize_size);
    auto read_image_3 = std::async(&BevDetSingle::readCvImage, this, camera_front_right, std::ref(raw_data_buffer->raw_data[2]), resize_size);
    auto read_image_4 = std::async(&BevDetSingle::readCvImage, this, camera_back_left  , std::ref(raw_data_buffer->raw_data[3]), resize_size);
    auto read_image_5 = std::async(&BevDetSingle::readCvImage, this, camera_back       , std::ref(raw_data_buffer->raw_data[4]), resize_size);
    auto read_image_6 = std::async(&BevDetSingle::readCvImage, this, camera_back_right , std::ref(raw_data_buffer->raw_data[5]), resize_size);
    read_image_1.wait();
    read_image_2.wait();
    read_image_3.wait();
    read_image_4.wait();
    read_image_5.wait();
    read_image_6.wait();

这里用到的库是#include <future>,将上述六个读取任务异步执行(使用async函数),使用wait()函数进行阻塞,也即只有任务执行完毕后才会执行下一条指令。

例 2:thread的简单使用

#include <iostream>
#include <thread>

void function1(){
    
    
    for(int i=0; i < 200; i++){
    
    
        std::cout << "+";
    }
}
void function2(){
    
    
    for (int i = 0; i < 200; i++){
    
    
        std::cout << "-";
    }
}
int main(){
    
    
    std::thread worker1(function1);
    std::thread worker2(function2);
    worker2.join(); // 阻塞主线程等待子线程结束
    worker1.join(); // 阻塞主线程等待子线程结束
}

这里用到的库是<thread>,通过将任务派发给worker,可以提升程序的执行效率,类似的,join()也是起到了阻塞作用。

猜你喜欢

转载自blog.csdn.net/weixin_45910027/article/details/130872865
今日推荐