C++知識點(1)_thread庫

C++11之後有了標準的線程庫,std::thread,通過創建一個thread對象來管理c++程序中的多線程。
通常會看到pthread,這是linux下c++線程庫,提供一些線程的操作,偏向底層。對於多線程必須明白線程安全、線程同步和互斥關係、線程如何通信、與進程間的關係等,否則會陷入以下迷茫:
(1)程序死鎖,不響應
(2)執行結果達不到預期
(3)多線程性能並無提升執行效率
(4)理不清程序執行流程
(5)不知道如何調試,同上
今天的案例是在進行LeGo-LOAM中地圖優化代碼閱讀時,對於多線程的程序執行問題的疑問,通過模仿地圖優化執行寫了以下demo,希望能夠幫助自己理解多線程的程序執行問題。

#include<iostream>
#include<thread>
#include<string>
using namespace std;
class CTest
{
public:
    CTest(){cout<<"000"<<endl;}
    int tstart(const string& tname)
    {
        cout<<"thread t1!"<<tname<<endl;
        return 0;
    }
    int tend(const string& tname)
    {
        cout<<"thread t2!"<<tname<<endl;
        return 0;
    }
    int run (int j)
    {
        cout<<"run"<<j<<endl;
        return 0;
    }
    };

int main()
{ 
    CTest obj;
    /*關於參數的說明:
    參數1類型爲成員函數的函數指針
    參數2類型爲指向該類型的實例的指針
    參數3爲傳入的函數參數
    */
    thread t1(&CTest::tstart,&obj,"111");//參數1:線程函數,
    thread t2(&CTest::tend,&obj,"222");

    for(int i=0;i<5;i++)
    {
        obj.run(i);
    }
    //join線程,調用該函數會阻塞當前線程,知道*this所標識的線程執行完畢,join才返回
    t1.join();
    t2.join();
    cout<<"Main function!"<<endl;
    return 0;
}

程序執行結果:

000
run0
run1
run2
run3
run4
thread t1!111
thread t2!222
Main function!

CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
project(test1)
set(CMAKE_BUILD_TYPE "-Release")
add_compile_options(-std=c++11 -g -Wall)
add_executable(test1 test1.cpp)
target_link_libraries(test1 pthread)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章