"纯称为QUOT虚方法;实施升压时::线程封装接口 [英] "pure virtual method called" when implementing a boost::thread wrapper interface

查看:156
本文介绍了"纯称为QUOT虚方法;实施升压时::线程封装接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小包装这集中有什么相对于螺纹:

I have a small wrapper which centralize what's relative to threads :

class Thread {
protected:
    boost::thread *m_thread;

    virtual void work() = 0;

    void do_work() {
        work();
    }

public:
    Thread() : m_thread(NULL) {}
    virtual ~Thread() {
        catch_up();
        delete m_thread;
    }

    inline void catch_up() {
        if(m_thread != NULL) {
            m_thread->join();
        }
    }

    void run() {
        m_thread = new boost::thread(boost::bind(&Thread::do_work, boost::ref(*this)));
    }
};

当我实现它,说有以下内容:

When I implement it, say with the following :

class A : public Thread {
    void work() {}
};

A a; a.run();

我得到了pretty纯称为虚拟方法运行时终止显示。我认为这是升压::绑定的说法,但我不知道怎么说使用纯虚拟执行...

I got a runtime termination with a pretty "pure virtual method called" displayed. I think it's the boost::bind argument, but I don't know how to say "Use virtual pure implementation"...

由于aforehand。

Thanks aforehand.

问候,

老总空军终于

推荐答案

您崩溃发生,只有当你的程序立即退出:调用它的 A类的析构函数完成的之前<调用Thread的析构函数的 / em>的新开工线程必须安排一个机会。然后线程调用虚拟函数,但A类已不存在,所以它attemps调用Thread的do_work(),该函数调用纯虚功()。这里的额外输出程序:

Your crash happens only when your program exits immediately: it calls class A's destructor which finishes and calls Thread's destructor before the newly started thread had a chance to be scheduled. The thread then calls your virtual function, but class A no longer exists, so it attemps to call Thread's do_work(), which calls the pure virtual work(). Here's your program with extra outputs:

run() started 
run() ended
~A() started
~A() ended
~Thread() started
catch_up() started
do_work() started
pure virtual method called

标准的角度来看,我认为这是不确定的行为,因为该对象的生命周期已经结束(析构函数调用开始)时,它(参考的boost :: REF(*此))被用来调用从线程do_work()

Standard-wise, I think this is undefined behavior because the object's lifetime has already ended (destructor call began) when a reference to it (boost::ref(*this)) was used to call do_work() from the thread.

解决方案:让你自毁的对象之前,你的线程中执行:

Solution: let your thread execute before you destruct your object:

A a; a.run();
a.catch_up();

或者,如boost.thread文档中说,助推用户。螺纹必须确保引用的目标会超越执行的新创建的线程。

这篇关于&QUOT;纯称为QUOT虚方法;实施升压时::线程封装接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆