代码之家  ›  专栏  ›  技术社区  ›  laura

在析构函数中加入boost::thread实例

  •  9
  • laura  · 技术社区  · 16 年前

    类声明(为了简洁起见,我去掉了try/catch的run()方法:根据boostthread文档,无论有没有它,结果都应该相同):

    class B 
    {
    public:
        void operator()(){run();}
        void run();
        void shutdown();
        ~B();
        B();
        boost::thread *thr;
        bool shutdown_requested;
    };
    
    void B::shutdown()
    {
        shutdown_requested = true;
    
        if (thr != NULL)
        {
            thr->interrupt();
            thr->join(); // deadlock occurs here!
            delete thr;
            thr = NULL;
        }
    }
    
    B::~B()
    {
        shutdown();
    }
    
    B::B()
    {
        thr = new boost::thread(boost::ref(*this));
    }
    
    void B::run()
    {
        while (!shutdown_requested)
        {
            boost::xtime xt;
            boost::xtime_get(&xt, boost::TIME_UTC);
            xt.sec += 30;
            boost::this_thread::sleep(xt);
        }
    }
    

    不起作用的代码段:

    int main()
    {
        B *b = new B;
    
        Sleep(5000);
        printf("deleting \n");fflush(stdout);
    //    b->shutdown();
        delete b;
        printf("done\n");fflush(stdout);
    
        return 0;
    }
    

    有效的代码段:

    int main()
    {
        B *b = new B;
    
        Sleep(5000);
        printf("deleting \n");fflush(stdout);
        b->shutdown();
        delete b;
        printf("done\n");fflush(stdout);
    
        return 0;
    }
    

    所引用的对象的寿命超过 新创建的执行线程。

    1 回复  |  直到 16 年前
        1
  •  4
  •   laura    16 年前

    我发现了一个问题:它归结为一个过于热心的程序员。

    我最初是用杜马编译我的项目的( http://sourceforge.net/projects/duma/

    删除所有内存泄漏检测后,一切正常。