第二课:C++创建多线程

本文介绍了四种在C++中创建线程的方法:1)使用普通函数;2)利用Lambda表达式;3)传递不同类型的参数,包括普通参数、引用和智能指针;4)通过类的成员函数创建线程。每种方法都展示了如何启动线程、传递参数以及确保线程执行完毕。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

NO.1、普通函数充当线程函数创建线程

#include<thread>
#include<iostream>

using namespace std;
using namespace this_thread;

void print()
{
    cout<<"线程处理函数启动"<<endl;
}

void test1()
{
    thread t1(print);  //用thread创建线程
    t1.join();         //用join()线程处理函数
}

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

NO.2、采用Lambda表达式充当线程处理函数

#include<thread>
#include<iostream>

using namespace std;
using namespace this_thread;

void test2()
{
    thread t1([](){cout<<"Lambda表达式充当线程处理函数"<<endl;})
    t1.join();
}

int main()
{
    
     test2();

    return 0;
}

NO.3、带参函数创建线程

3.1、普通叁数

#include<thread>
#include<iostream>

using namespace std;
using namespace this_thread;

void printDate(int num)      //可以使用:comst int num
{
    cout<<"id:"<<num<<endl;
}

void test3()
{
    int num = 1;
    
    thread t1(printDate,num);     //第一个参数函数名,函数传参
    t1.join();
}

int main()
{

     test3();    
    return 0;
}

3.2、传引用

针对于引用变量 int &num 传叁问题,需要ref()包装引用作为转递的值

#include<thread>
#include<iostream>

using namespace std;
using namespace this_thread;

void printReference(int &num)     //可以使用:const int &num
{
    num = 100;
    cout<<"子线程:"<<num<<endl;
}

void test4()
{
   int num = 0;
    thread t1(printReference,ref(num));     //需要ref():包装引用作为转递的值
    t1.join();
}

int main()
{

     test4();

    return 0;
}

3.3、智能指针当函数

针对于unique_ptr<int> pty传叁问题,需要move()去传数据,在主线程得到数据是空的值

#include<thread>
#include<iostream>

using namespace std;
using namespace this_thread;

void printPtr(unique_ptr<int> pty)
{
    cout<<"智能指针:"<<*ptr.get()<<endl;
}

void test5()
{
    unique_ptr<int> ptr(new int(100));
    cout<<"test5:"<<ptr.get()<<endl;
    thread t1(printPtr,move(ptr));         //需要move()去传数据,在主线程得到数据是空的值
    t1.join();
    cout<<"得到空数据:"<<ptr.get()<<endl;
}

int main()
{

test5();

return 0;
}

NO.4、通过类中的成员函数去创建

4.1,仿函数形式:类名的方式调用

#include<thread>
#include<iostream>

using namespace std;
using namespace this_thread;

class Function
{
  public:
    void operator()()
    {
        cout<<"重载()"<<endl;
    }
};

void test6()
{
    //对像
    Function object;
    thread t1(object);
    t1.join();
    
    //匿名对像
    thread t2((Function()));  
    t2.join();
}

int main()
{

     test6();
    
    return 0;
}

4.2、普通类中的成员函数

#include<thread>
#include<iostream>

using namespace std;
using namespace this_thread;

class MM
{
  public:
    void print(int &id)
    {
        cout<<"id:"<<id<<endl;
    }
};

void test7()
{
    MM mm;
    int id = 1;
    thread t1(&MM::print,mm,ref(id));
    t1.join();
}

int main()
{

     test7();
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值