C++之多線程編程

C++之多線程編程

學多線程的主要原因是疫情來臨,每天在家實在是啥也不相干,論文寫不出來,就說提升一下編程技能吧。

學多線程的主要目的:

  • 研究方向是多傳感器融合SLAM算法,SLAM系統對實時性要求比較高,大多數SLAM開源系統都使用了多線程技術。
  • 在公司實習一段時間,潛移默化中天天聽到數據的高併發這些詞語,因爲公司這塊數據量比較大。

所以決定了解一下多線程編程。

下面這篇博客看完可以直接上手最簡單的基礎多線程編程。

std::thread(c++)傻瓜教程

下面這篇博客講的非常好,我搜了一堆他講的最好。這也讓我想到鵬哥經常和我說的話:學啥東西,一定要學會講給別人聽,你要是能讓給小白講明白才說明你學懂了。

淺談C++中的多線程編程(一)

線程:調度、分配的基本單位

進程:獨立分配資源的單位

線程參與操作系統的調度,參與CPU的競爭,得到分配時間,獲得CPU運行;進程負責獲取操作系統分配的資源。

多線程不一定比單線程快,C++11開始支持多線程,

併發:在同一個時間裏CPU同時執行兩條和多條命令。

併發的物理基礎:主要是計算機的多核CPU的發展。

編程實現

main.cpp

// thread example
#include <iostream>  // std::cout  std::cin
#include <thread>    // std::thread
#include <mutex>
//using namespace std;
std::mutex mymutex;   //加入鎖
void foo() {
    // do stuff...
    std::unique_lock<std::mutex> lock(mymutex);
    for (int i = 0; i < 100; ++i) {
        std::cout << "foo()  i: " << i << "\n";
    }
}
void bar(int x) {
    // do stuff...
    std::unique_lock<std::mutex> lock(mymutex);
    for (int j = x; j < 200; ++j) {
        std::cout << "bar()  j: " << j << "\n";
    }
}
int main() {
    std::cout << "main, foo and bar now execute concurrently...\n\n";
    std::thread first(foo);        // spawn new thread that calls foo()
    std::thread second(bar, 100);  // spawn new thread that calls bar(0)

    // synchronize threads:
    first.join();   // 阻塞函數
    second.join();  // pauses until second finishes
    std::cout << "foo and bar completed.\n\n";
    //std::cin.get();
    return 0;
}

CMakeLists

cmake_minimum_required(VERSION 3.5)
project(update_quaternion)

set(CMAKE_BUILD_TYPE "Debug")
set(CMAKE_CXX_FLAGS "-std=c++11 -o3")

add_executable(update_quaternion main.cpp )
target_link_libraries(update_quaternion -lpthread)

注意加入-lpthread,不然會出現以下錯誤

在函數‘std::thread::thread<void (*)()>(void (*&&)())’中:
/usr/include/c++/5/thread:137:對‘pthread_create’未定義的引用

在這裏插入圖片描述

第一張圖是加了mutex,第二張圖是去掉mutex.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章