c++11 std::threads创建多线程的三种方式
在C++11 标准中,添加了很多的新特性,当用户在创建多线程程序时,可以有更多的选择。
创建线程的三种方式:
1.) 函数指针
2.) 函数类型
3.) Lambda 函数
1 函数指针
void foo1(int param1, int param2, int& param3){
param3=param1+param2;
std::cout<<"Method Function Pointer at thread number:\t"<<std::this_thread::get_id()<<std::endl;
//std::cerr<<param3<<std::endl;
}
std::thread th1(foo1,1,2,std::ref(num_return1));
2 函数类
class func{
public:
void operator()(int param1,int param2,int& param3)
{
param3=param1+param2;
std::cout<<"Method Function Object at thread number:\t"<<std::this_thread::get_id()<<std::endl;
}
};
std::thread th2(func(),3,4,std::ref(num_return2));
3 lamda
详细的lamda表达式的介绍请看 微软官方英文文档
std::thread th3([](){ std::cout<<"Method Lambda \t\t\tat thread number:\t"<<std::this_thread::get_id()<<std::endl; });
完整代码
// 这个主要用来展示创建多线程函数
// Created by allen on 2020/6/24.
//
#include <iostream>
#include <thread>
/***
* 第一种方式:使用函数指针
*/
void foo1(int param1, int param2, int& param3){
param3=param1+param2;
std::cout<<"Method Function Pointer at thread number:\t"<<std::this_thread::get_id()<<std::endl;
//std::cerr<<param3<<std::endl;
}
/***
* 第二种方式: 使用函数创建线程
*/
class func{
public:
void operator()(int param1,int param2,int& param3)
{
param3=param1+param2;
std::cout<<"Method Function Object at thread number:\t"<<std::this_thread::get_id()<<std::endl;
}
};
int main(int argc,char** argv){
int num_return1,num_return2;
std::thread th1(foo1,1,2,std::ref(num_return1));
th1.join();
//th1.detch();
std::thread th2(func(),3,4,std::ref(num_return2));
th2.join();
std::thread th3([](){
std::cout<<"Method Lambda \t\t\tat thread number:\t"<<std::this_thread::get_id()<<std::endl;
});
th3.join();
std::cout<<"Method Function Pointer return \t"<<num_return1<<std::endl;
std::cout<<"Method Function Object return \t"<<num_return2<<std::endl;
return 0;
}
函数执行输出:
/home/allen/CLionProjects/ThreeWay-MulthThreadDemo/cmake-build-debug/ThreeWay_MulthThreadDemo
Method Function Pointer at thread number: 139648041760512
Method Function Object at thread number: 139648041760512
Method Lambda at thread number: 139648041760512
Method Function Pointer return 3
Method Function Object return 7Process finished with exit code 0
如果使用Cmake编译程序,请参考这篇文章: