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; }