cpp 併發編程小計

Cpp 併發編程小計

大都是搬運,算是參考時方便些

1.1 在類中使用 pthread,不是 static 的方法很難使用,找了個方法。可是很醜陋。

1.2 直接使用 std::thread使用 this第一次沒仔細看, 發現可以直接使用類的非 static 類。話說,當初爲嘛沒看出來…

1.3 再進一步
用C++11的std::async代替線程的創建

1.4 C++ 多線程下的: error C3867: 使用 “&” 來創建指向成員的指針
“&” 同樣適用於 async

1.5 實例程序

#include <iostream>
//#include <thread>
#include <future>

using namespace std;

class HelloWorld
{
public:
    bool init();
    int myThread(int first, int second);
};

bool HelloWorld::init()
{
    //std::thread t1(&HelloWorld::myThread, this, 10, 20);//創建一個分支線程,回調到myThread函數裏
    //t1.join();
    ////t1.detach();

    std::future<int> f1 = std::async(std::launch::async, &HelloWorld::myThread, this, 1, 2);
    cout << f1.get() << endl; //output: 8

    printf("in major thread");//在主線程
    return true;
}

int HelloWorld::myThread(int first, int second)
{
    printf("in my thread,first = %d,second = %d", first, second);
    return first + second;
}

int main()
{
    HelloWorld hello;
    hello.init();
    return 0;
}

1.6 小結

使用 async 可以獲得我們想要的 – 同步,且能獲取返回值

1.7 還是用的太少了,出現了 “error C2064: term does not evaluate to a function taking 0 arguments” 錯誤。下面的代碼很好的說明了出現的問題

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

int plainHello(){
    cout << "hello is always ok" << endl;
    return 0;
}


class Hello{
public:
    Hello(){};
    ~Hello(){};

    void say(){
        cout << "hei in hello" << endl;
    }

    static void staticSay(){
        cout << "static say is also ok" << endl;
    }
};


int main()
{
    thread t1(plainHello);  //直接調用不會有問題
    t1.join();

    //thread t2(&Hello::say);   //編譯出錯,error C2064: term does not evaluate to a function taking 0 arguments。是說沒有提供類的實例
    //t2.join();

    Hello hello;
    thread t3(&Hello::say, &hello); //提供了類的實例,可以正確找到調用的方法
    t3.join();

    thread t4(&Hello::staticSay);   //靜態方法,不提供類的實例
    t4.join();

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