深入学习c++--多线程编程(三)thread的两种死法

1. 生成了一个线程,需要告诉编译器是否管理

必须告诉编译器是不管理还是管理,否则直接down了

#include <iostream>
#include <thread>
#include <chrono>
#include <future>
#include <atomic>
#include <cmath> 
#include <vector>
#include <cstdlib>
#include <string>
#include <mutex>
using namespace std; 

void joinWorker()
{
    
}

void detachWorker()
{
}

class Obj {
    public:
        Obj() {
            cout << "hello\n";
        }
        ~Obj() {
            cout << "world\n";
        }
};

int main()
{
    Obj obj;
    thread j(joinWorker);       //程序直接down了,析构函数都没有调用 

    return 0;
}

1.1 可以通过join(),自己管理

int main()
{
    Obj obj;
    thread j(joinWorker);       
    
    if (j.joinable())
        j.join();

    return 0;
}

如果遇到异常,没有调用join,自己可以写一个析构调用join()

class ThreadGuard {
    public:
        ThreadGuard(thread& t) : m_thread(t) {
        } 
        ~ThreadGuard() {
            if (m_thread.joinable())
                m_thread.join();
        } 
    private:
        thread& m_thread;
}; 

1.2 通过detach(),不管理

detach适合不会出错,生命周期比整个程序短,不想管理的程序

#include <iostream>
#include <thread>
#include <chrono>
#include <future>
#include <atomic>
#include <cmath> 
#include <vector>
#include <cstdlib>
#include <string>
#include <mutex>
using namespace std; 

class Obj {
    public:
        Obj() {
            cout << "hello\n";
        }
        ~Obj() {
            cout << "world\n";
        }
};

void joinWorker()
{
}

void detachWorker()
{
    Obj obj;
}



int main()
{
//    Obj obj;
    thread j(joinWorker);       
    thread w(detachWorker);
    w.detach();
    
    
    if (j.joinable())
        j.join();
        
//    w.join();    // w线程不能再join() 

    return 0;
}

如果程序执行时间长,则可能不会调用析构函数

void detachWorker()
{
    Obj obj;
    this_thread::sleep_for(chrono::seconds(1));
}

猜你喜欢

转载自www.cnblogs.com/douzujun/p/10841797.html