【C++】多线程中调用函数的方法

在多线程中调用函数的方法:

以函数名和函数参数作为输入对象来构造线程对象:t2 t4 t6 t7

通过lambda表达式调用函数,将函数作为lambda表达式的内容: t1 t3 t5

#include <iostream>
#include <thread>
#include <string>

void printAll(int a, int b, int c)
{
    std::cout << a << " " << b << " " << c << std::endl;
}
void add(int a, int b, int&c)
{
    c += a + b;
}

void printString(const std::string& info, const std::string& info2)
{
    std::cout << "hello " << info << " " << info2 << std::endl;
}

void testThreadInit()
{
    int a = 1;
    int b = 2;
    int c = 3;
    std::cout << "t1: ";
    std::thread t{[=]{printAll(a,b,c);}};//通过lambda表达式调用函数printALL,[=]表示将所需要参数按值拷贝
    t.join();
    std::cout << "t2: ";
    std::thread t2(printAll,a,b,c);//通过线程对象的构造函数调用printALL,参数全部按值拷贝
    t2.join();

    std::cout << "t3: ";
    std::thread t3([=,&c]{add(a,b,c);});//通过lambda表达式调用add,并将c以引用形式调用
    t3.join();
    printAll(a,b,c);
    std::thread t4(add,a,b,std::ref(c));//通过构造函数调用add,通过ref(c)将c以&c的方式调用
    t4.join();
    std::cout << "t4: ";
    printAll(a,b,c);

    std::string abc("abc");
    std::string def("def");

    //t6的效率一定会比t5和t7的效率低,因为进行了一次string->const string的拷贝构造
    std::thread t5([&]{printString(abc,def);});//[&]表示以引用方式调用lambda表达式中所有需要的对象
    t5.join();
    std::thread t6(printString, abc, def);
    t6.join();
    std::thread t7(printString, std::cref(abc),std::cref(def));//cref(abc)将abc以const& 的形式进行调用
    t7.join();
}

int main()
{
    testThreadInit();
    return 0;
}

运行结果图下:

在这里插入图片描述

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值