1. C++11中的線程
1.1 線程的管理
一個進程中至少存在一個線程,這個線程被稱爲主線程,我們可以在任意線程中創建線程類的實例。
每個線程都需要一個入口函數,當入口函數返回時,線程就會退出,主線程的入口函數爲main()。
1.1.1 線程的啓動
線程的創建十分簡單,我們只需創建一個線程類的實例,併爲它傳入一個可調用對象(lambda表達式;std::function;重載了調用運算符的類;成員函數;普通函數),就可以啓動一個線程了:
class Work {
public:
void operator()() {
std::cout << "callable object" << std::endl;
}
};
void do_work {
std::cout << "working" << std::endl;
}
void test() {
std::thread worker0(do_work); //普通函數
worker0.detach();
std::thread worker1([]() { //lambda表達式
std::cout << "lambda call" << std::endl;
});
worker1.detach();
std::thread worker2(Work{}); //重載了調用運算符的類
worker2.detach();
}
參考文獻:
https://www.cnblogs.com/wangguchangqing/p/6134635.html
https://blog.csdn.net/hitwengqi/article/details/8015646
https://www.runoob.com/cplusplus/cpp-multithreading.html