1. 程式人生 > >深入學習c++--多線程編程(三)thread的兩種死法

深入學習c++--多線程編程(三)thread的兩種死法

sleep str world 線程編程 執行 mes obj future name

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));
}

技術分享圖片

深入學習c++--多線程編程(三)thread的兩種死法