zoukankan      html  css  js  c++  java
  • 深入学习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
    ";
            }
            ~Obj() {
                cout << "world
    ";
            }
    };
    
    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
    ";
            }
            ~Obj() {
                cout << "world
    ";
            }
    };
    
    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# 文件上传
    iOSswift基础篇1
    copyWithZone 的使用方法
    客户端登陆接收大量数据导致数据丢失问题解决方法
    设计模式观察者模式(KVO)
    SQLite 之 C#版 System.Data.SQLite 使用
    设计模式MVC(C++版)
    JS 创建自定义对象的方法
    手机号、邮箱、身份证号 格式 验证
    在.cs文件中添加客户端方法
  • 原文地址:https://www.cnblogs.com/douzujun/p/10841797.html
Copyright © 2011-2022 走看看