Create a thread with a class object (callable) approach (learning)

Other way to create a thread:
a class object (callable), operator will execute this function.

Such a program each time the results are not the same.
// thread using the Bureau of the main thread of invariants, after the main thread execution, i memory is recovered. I still use sub-thread references, unknown situation occurs.
Once the call detach (), TA object in the main thread is still there?
A: This object is gone, but it does not matter, because the object is copied into the child thread to go.
Ta after executing the main thread will be destroyed, but the copied object still exists.
So, as long as the child thread no reference or a pointer, then it will not be a problem.

class TA
{
public:
    void operator()()
    {
        cout<<"我的线程开始执行了"<<endl;
        cout<<"我的线程结束了"<<endl;
    }

};

int main()
{
   TA ta;
   thraed my_th(ta);//可调用对象
   my_th.join();
   
   cout<<"I LOve CHNIA"<<endl;
   return 0;

}


-------------------------------------------------


class TA
{
public:
    TA(int i):m_i(i){
        cout<<"TA构造函数执行"<<endl;
    }
    TA(const TA ta):m_i(ta.m_i)
    {
        cout<<"拷贝构造函数执行"<<endl;    
    }
    
    ~TA()
    {
        cout<<"TA析构函数执行"<<endl;
    }
    void operator()()
    {
        cout<<"m_i:"<<m_i<<endl;
        cout<<"m_i:"<<m_i<<endl;
        cout<<"m_i:"<<m_i<<endl;
        cout<<"m_i:"<<m_i<<endl;
    }
    int m_i;

};

int main()
{
   int i=6;
   TA ta(i);
   thraed my_th(ta);//可调用对象,拷贝了
   my_th.detach();
   
   cout<<"I LOve CHNIA"<<endl;
   return 0;

}


Use: lambda expression to create a thread

int main()
{
    auto mylambda = []
    {
    cout<<"我的线程开始执行了"<<endl;
    
    
    
    cout<<"我的线程结束了"<<endl;

    };
    thread myth(mylambda);
     myth.jion();
    cout<<"I LOve CHNIA"<<endl;
    return ;
}

 

Published 101 original articles · won praise 73 · views 120 000 +

Guess you like

Origin blog.csdn.net/usstmiracle/article/details/103673141