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

2021/11/6 22:10:25

本文主要是介绍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,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;

}



这篇关于c++创建线程注意事项(2)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程