c++ 多線程(2)創建線程對象的方法


@

一、用函數對象創建線程

// 用函數對象創建線程
#include <iostream>
#include <thread>
using namespace std;

void func(){
    cout<<"我的線程開始執行了"<<endl;
    //...
    cout<<"我的線程結束執行了"<<endl;
}

int main(){
    thread my_thread(func);
    my_thread.join();//等待子線程執行結束

    cout<<"I love China"<<endl;
    return 0;
}

二、用類對象創建線程

// 用類對象創建線程
#include <iostream>
#include <thread>
using namespace std;


// 類要變成可調用對象需要重載操作符()
class TA{
public:
    void operator()()//不能帶參數,代碼從這開始執行
    {
        cout<<"我的線程開始執行了"<<endl;
        //...
        cout<<"我的線程結束執行了"<<endl;
    }
};

int main(){

    TA ta;
    thread my_thread(ta);// ta 可調用對象
    my_thread.join();//等待子線程執行結束

    cout<<"I love China"<<endl;
    return 0;
}
// 用類對象創建線程
#include <iostream>
#include <thread>
using namespace std;


// 類要變成可調用對象需要重載操作符()
class TA{
public:
    int m_i;
    TA(int i):m_i(i){}
    void operator()()//不能帶參數,代碼從這開始執行
    {
        cout<<"我的線程"<<m_i<<"開始執行了"<<endl;
        //...
        cout<<"我的線程結束執行了"<<endl;
    }
};

int main(){
    int myi =6;
    TA ta(myi);
    thread my_thread(ta);// ta 可調用對象
    my_thread.join();//等待子線程執行結束

    cout<<"I love China"<<endl;
    return 0;
}

三、把某個類中的某個函數作為線程的入口地址

class Data_
{
public:
    void GetMsg(){}
    void SaveMsh(){}
};
//main函數里
    Data_ s;
    //第一個&意思是取址,第二個&意思是引用,相當於std::ref(s)
    //thread oneobj(&Data_::SaveMsh,s)傳值也是可以的
    //在其他的構造函數中&obj是不會代表引用的,會被當成取地址
    thread oneobj(&Data_::SaveMsh,&s);
    thread twoobj(&Data_::GetMsg,&s);
    oneobj.join();
    twoobj.join();

四、用lambda表達式創建線程

// 用lambda表達式創建線程
#include <iostream>
#include <thread>
using namespace std;


int main(){

    auto my_lambda = []  {
            cout<<"我的lambda表達式線程開始執行"<<endl;
    };
    thread my_thread(my_lambda);// ta 可調用對象
    my_thread.join();//等待子線程執行結束

    cout<<"I love China"<<endl;
    return 0;
}


免責聲明!

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



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