c++创建线程注意事项(2)

  • 线程ID:std::this_thread::get_id()获取线程ID
  • 传递类对象时:虽然线程入口采用引用接收,但并不是真实的引用,而是相当于值传递,要调用一次拷贝构造;只有在传参时加上std::ref()才是真实的引用
  • 当传入智能指针时,需要使用std::move()转换
  • 用类的成员函数作为线程参数 (参数分别为 &成员函数名,对象名,参数)
#include <iostream>
#include <thread>
using namespace std;

class A
{
public:
    int m_i;
    A(int a):m_i(a){
        cout<<"构造函数执行,地址为:"<<this<<"   thread_ID: "<<std::this_thread::get_id()<<endl;
    }

    A(const A &a):m_i(a.m_i){
        cout<<"拷贝构造函数执行,地址为:"<<this<<"   thread_ID: "<<std::this_thread::get_id()<<endl;
    }

    void thread_word(int num)
    {
        cout<<"子线程3开始"<<endl;
        cout<<"子线程3参数地址是:"<<this<<"   thread_ID: "<<std::this_thread::get_id()<<endl;

        cout<<"子线程3结束"<<endl;
    }

    ~A(){
        cout<<"析构函数执行,地址为:"<<this<<"   thread_ID: "<<std::this_thread::get_id()<<endl;
    }
};

void myprint(const A &buff)
{
    cout<<"子线程开始"<<endl;
    cout<<"子线程参数地址是:"<<&buff<<"   thread_ID: "<<std::this_thread::get_id()<<endl;
    cout <<"buff.m_i="<< buff.m_i<<endl;
    cout<<"子线程结束"<<endl;
}
void myprint2(unique_ptr<int> buff)
{
    cout<<"子线程2开始"<<endl;
    cout<<"子线程2参数地址是:"<<&buff<<"   thread_ID: "<<std::this_thread::get_id()<<endl;

    cout<<"子线程2结束"<<endl;
}
int main()
{
    cout <<"主线程开始"<<"   thread_ID: "<<std::this_thread::get_id()<<endl;
   int num=2;
   A myobj(num);
   //thread thread1(myprint,myobj);//虽然是用引用接收参数,但依然会对原对象复制一份,如果想采用主线程中的对象,需要调用std::ref(myboj)
    thread thread1(myprint,std::ref(myobj));//不会调用拷贝构造,共享主线程的对象
    thread1.join();

     //智能指针作为参数传递
    unique_ptr<int> myptr(new int(100));
    thread thread2(myprint2,std::move(myptr));
    thread2.join();

    //用类的成员函数作为线程参数   (参数分别为成员函数,对象,参数)
    thread thread3(&A::thread_word,myobj,15);
    thread3.join();
    cout<<"主线程结束"<<endl;
    return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值