【发布时间】:2016-02-17 15:22:37
【问题描述】:
我希望在基类中运行一个线程,该线程不断调用该类中被派生类覆盖的纯虚方法。
对于启动线程,我没有问题,因为我可以在构造完 HasInitalized() 函数后调用它。因此,线程在类完全构建后启动。
但是,由于类的生命周期由 shared_ptr 管理,因此我无法调用类似的方法来停止线程。如果我在析构函数中停止线程,它将导致段错误,因为派生类在基类之前被销毁,因此会尝试调用不存在的函数。
我知道我可以从派生类调用停止函数,但我不想在派生类的每个实例上都调用。
有没有办法解决这个问题。
例子:
#include "boost/thread.hpp"
class BaseClass
{
public:
BaseClass()
{
}
// Start the thread
void Start()
{
_thread = boost::thread(&BaseClass::ThreadLoop, this);
}
virtual ~BaseClass()
{
_thread.interrupt();
_thread.join();
}
private:
// Will loop until thread is interupted
void ThreadLoop()
{
try
{
while(true)
{
DoSomethingInDerivedClass();
boost::this_thread::interruption_point();
}
}
catch(...)
{
}
}
boost::thread _thread;
protected:
virtual void DoSomethingInDerivedClass() = 0;
};
class DerivedClass : public BaseClass
{
DerivedClass()
{
}
~DerivedClass()
{
// This gets called before base class destructor.
}
protected:
void DoSomethingInDerivedClass();
};
【问题讨论】:
-
在任何情况下,您都将在派生对象上工作,并在 Base 上进行多态工作。因此,挂起线程的逻辑必须从 Derived 类析构函数中调用。实现暂停/线程关闭的实际功能可以在基类中实现。
-
你应该重新考虑你的设计。您的 DerivedClasses 至少有两个职责。从基础继承的线程控制和你的算法来做这项工作。你应该把这个分开。通过接口将派生类传递给 Thread 类。这样可以避免问题。
-
我认为您的设计/策略不正确,只是看起来不正确。
标签: c++ multithreading boost