C++11/std::thread - 可作爲線程函數的幾種方式總結

1 使用普通函數作爲線程函數

代碼示例:

#include <iostream>
#include <thread>

void ThreadFunction()
{
    std::cout<< "線程函數被啓動" << std::endl;
}


int main()
{
    std::thread thread(ThreadFunction);

    thread.join();

    getchar();
    return 0;
}

2 使用類的成員函數作爲線程函數

代碼示例:

#include <iostream>
#include <thread>


class ThreadFunc
{
public:
    void ThreadFunction()
    {
        std::cout << "線程函數被啓動" << std::endl;
    }
};

int main()
{
    ThreadFunc m_ThreadFunc;

    std::thread thread(&ThreadFunc::ThreadFunction,&m_ThreadFunc);

    thread.join();

    getchar();
    return 0;
}

3 Lambda表達式/匿名函數作爲線程函數

代碼示例:

#include <iostream>
#include <thread>


int main()
{
    std::thread thread{ [] {std::cout << "線程函數被啓動" << std::endl; } };

    thread.join();

    getchar();
    return 0;
}

未完待續。

大家有興趣可以訪問我的個站:www.stubbornhuang.com

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