C++11线程
- 線程存在的意義
- 線程創(chuàng)建
- join 與 detach
- 測試你的電腦能開多少個線程
線程存在的意義
其存在的意義就是:單核并發(fā),多核并行,避免了主線程的阻塞。
線程創(chuàng)建
C++線程的啟動,只需要#include <thread>即可。線程對象的創(chuàng)建,意味著線程的開始。
代碼演示:
#include <iostream> #include <thread>using namespace std;void func() {cout << "thread id:" << this_thread::get_id() << endl;cout << "do some work" << endl;// sleep(3);this_thread::sleep_for(chrono::seconds(10)); } int main() {cout << "main thread id:" << this_thread::get_id() << endl;thread t(func); //將func函數(shù)注冊為線程,線程對象生成自動執(zhí)行。t.join(); //等待次線程執(zhí)行完成后進行次線程資源回收cout << "main thread is waiting thread" << endl;return 0; }運行結(jié)果:
注冊線程帶參數(shù):
代碼演示:
運行結(jié)果:
join 與 detach
t.join用于對子線程釋放時的資源進行回收。
main函數(shù)所在的線程為主線程。
子線程依賴于父線程存在。
t.detach標識線程分離。
讓子線程和主線程脫離關(guān)系,主線程也不會對于子線程釋放時的資源進行回收。
detach 后的線程,不能直接再join,是否可以 join 可以通過 joinable 來判斷。
代碼演示:
#include <iostream> #include <thread>using namespace std;void func(int n, string s) {cout << "thread id:" << this_thread::get_id() << endl;cout << "do some work" << endl;for (int i = 0; i < n; i++){cout << s << endl;}this_thread::sleep_for(chrono::seconds(5)); }int main() {cout << "main thread id:" << this_thread::get_id() << endl;int n = 6;string str = "china";thread t(func, n, str);this_thread::sleep_for(chrono::seconds(10));t.detach();if (t.joinable()){t.join();cout << "t.join();" << endl;}else{cout << "no able join" << endl;}cout << "main thread is waiting thread" << endl;return 0; }運行結(jié)果:
使用detach的場景:
主線程等待回收資源的子線程數(shù)量有限,detach 則不會等待主線程回收,可以源源不斷的產(chǎn)生子線程,使用完成后直接丟棄。
join的執(zhí)行是阻塞等待。
代碼演示:
運行結(jié)果:
可以看到,雖然bar線程先結(jié)束,但是由于join阻塞等待,所以foo線程先回收。
測試你的電腦能開多少個線程
代碼演示:
#include <iostream> #include <thread> #include <chrono> using namespace std; #define N 1000 void foo() {// 模擬昂貴操作this_thread::sleep_for(chrono::seconds(5));cout << "foo!\n"; } int main() {thread th[N];for (int i = 0; i < N; i++){th[i] = thread(foo);}for (auto& t : th)t.join();cout << "done!\n"; }運行結(jié)果:
可以自行修改N來測試自己的電腦能開多少個線程。
總結(jié)
- 上一篇: core dump 崩溃分析
- 下一篇: C++11条件变量