C++多線程的三種創建方式
- 2020 年 2 月 16 日
- 筆記
C++11的新特性std::thread的創建方式主要有:函數指針,類或結構體,lambda表達式。下面將會附上這三種創建線程方式的code。
首先第一個是通過函數指針的方式來創建:
不帶參數:
#include <iostream> #include <thread> using namespace std; void A() { cout << "this is A thread" << endl; } int main() { thread t(A); t.join(); cout << "this is main thread" << endl; return 0; }
帶參數:
#include <iostream> #include <thread> using namespace std; void A(int a,int b) { cout << "this is A thread" << endl; } int main() { thread t(A, 2, 3); t.join(); cout << "this is main thread" << endl; return 0; }
第二種是通過類和結構體來創建,那麼對於類來說結構體就相當於一個訪問限定符為public的類,那麼下面就以類來舉例。類的對象是不能通過像函數那樣直接去創建線程的,那麼就需要對()進行運算符重載,使其變為一個仿函數,從而再去通過這個入口去創建線程。
不帶參數:
#include <iostream> #include <thread> using namespace std; class A { public: void operator()() const{ cout << "this is A thread" << endl; } }; int main() { thread t1{A{}}; t1.join(); A a; thread t2(a); t2.join(); thread t3 = thread(A()); t3.join(); cout << "this is main thread" << endl; return 0; }
帶參數:
#include <iostream> #include <thread> using namespace std; class A { public: A(int a,int b) : m_iA(a), m_iB(b) {} void operator()(int a,int b) const{ cout << a + b << endl; cout << m_iA + m_iB << endl; cout << "this is A thread" << endl; } private: int m_iA; int m_iB; }; int main() { // 下列輸出均為5 3 thread t1{ A{1,2} ,2, 3}; t1.join(); A a(1, 2); thread t2(a, 2, 3); t2.join(); thread t3 = thread(A(1, 2), 2, 3); t3.join(); cout << "this is main thread" << endl; return 0; }
第三種就是通過lambda表達式進行創建,其實lambda和函數指針的方法是差不多的,先來看一下比較簡單的lambda的不帶參數的創建線程的方法:
#include <iostream> #include <thread> using namespace std; int main() { auto f = [] { cout << "This is f thread" << endl; }; thread t(f); t.join(); cout << "this is main thread" << endl; return 0; }
為了方便,我們也可以這麼去寫:
#include <iostream> #include <thread> using namespace std; int main() { thread t = thread([]{ cout << "This is f thread" << endl; }); t.join(); cout << "this is main thread" << endl; return 0; }
帶上參數就可以這麼去寫:
#include <iostream> #include <thread> using namespace std; int main() { int a = 1; thread t = thread([a](int b,int c){ cout << a + b + c << endl; // 輸出為6 cout << "This is f thread" << endl; }, 2, 3); t.join(); cout << "this is main thread" << endl; return 0; }