c++11 std::threads创建多线程的三种方式

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     7

Process finished with exit code 0
 

如果使用Cmake编译程序,请参考这篇文章:

Cmake编译pthreads报错:undefined reference to pthread_create

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值