如何创建运行抽象类成员函数的std :: thread?

时间:2015-09-22 09:42:46

标签: multithreading templates c++11 polymorphism virtual

我有一些事情:

class Parent
{
private:
    std::thread t1;
protected:
    void ThreadFunction()
    {
        while(true)
        {
            SpecializedFunction();
        }
    }
    void CreateThread()
    {
        t1 = std::thread(&Parent::ThreadFunction, *this);
    }
    virtual void SpecializedFunction() = 0;
public:
    void Run()
    {
        CreateThread();
    }
}

class Child1 : public Parent
{
protected:
    void SpecializedFunction()
    {
        //code
    }
}

class Child2 : public Parent
{
protected:
    void SpecializedFunction()
    {
        //code
    }
}

但我有编译错误(如果我评论线程创建行,它会编译)。它说它不能专门化衰变方法。我认为问题是父是抽象的,要么线程函数受到保护,但我不确定。你能建议一个解决方法/解决方案吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

*this

这将创建 t1 = std::thread(&Parent::ThreadFunction, this); 的副本并在副本上运行成员函数。在您失败的情况下,因为您无法创建抽象类的副本,但是制作副本可能不是您想要的。

要在现有对象上运行线程,请传递一个指针:

    t1 = std::thread(&Parent::ThreadFunction, std::ref(*this));

或参考:

~Parent() { t1.join(); }

作为T.C.在上面的评论中说,您必须确保在新线程仍在运行时对象的生命周期不会结束。您可以通过在析构函数中加入它来完成此操作:

std::thread

(如果您在销毁之前没有加入predicate,您的计划将立即终止!)

这仍然不是引用安全的,因为它只能确保在线程仍在运行时不会销毁 base 类,但是线程可能正在访问派生类,因此您可能需要确保该线程在派生的析构函数中加入。

相关问题