1. 程式人生 > >c++11的多執行緒支援一(執行緒啟動)

c++11的多執行緒支援一(執行緒啟動)

支援多執行緒程式設計,是c++11的一個新特性。在語言層面編寫多執行緒程式,程式的可移植性得到很大提高。

新的執行緒庫通過std::thread管理執行緒的執行,啟動執行緒的方式有兩種:

1、以一個函式地址為引數,例項化一個std::thread物件;

2、通過一個類的例項構造一個std::thread物件,用於構建std::thread的類必須實現了operator()方法。

一旦傳入的函式返回,執行緒終止。下面以一個例項說明:

#include <iostream>
#include <thread>

void fun()
{
    std::cout << "method one: thread start" << std::endl;
    std::cout << "method one: thread stop" << std::endl;
}

class run
{
public:
    void operator()()
    {
        std::cout << "method two: thread start" << std::endl;
        std::cout << "method two: thread stop" << std::endl;
    }
};

int32_t main()
{
    // one method of launching thread
    std::thread t_1(fun);
    std::cout << "method one: start test thread" << std::endl;
    t_1.join();
    std::cout << "method one: over" << std::endl;

    // the other method of launching thread
    run r;
    //std::thread t_2(r);  // 1. this actually copies the supplied object into the thread.
    std::thread t_2(std::ref(r));  // 2. if you want to use the object you supplied, you can do so by wrapping it in std::ref.
    std::cout << "method two: start test thread" << std::endl;
    t_2.join();
    std::cout << "method two: over" << std::endl;
    return 0;
}
執行後,這段程式碼的輸出為:

method one: start test thread
method one: thread start
method one: thread stop
method one: over
method two: start test thread
method two: thread start
method two: thread stop
method two: over