ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2021-11-06 21:03:39  阅读:117  来源: 互联网

标签:std cout thread int c++ 线程 注意事项 参数


  • 线程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,std::ref(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;

}

标签:std,cout,thread,int,c++,线程,注意事项,参数
来源: https://blog.csdn.net/qq_45601625/article/details/121184822

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有