我有一个基类,它充当同步事件处理的多种策略的接口。我现在想要异步处理事件的策略。为了尽量减少代码重构,每个策略都有自己的内部线程用于异步事件处理。我主要关心的是如何管理这个线程的生命周期。派生策略类在代码库周围构建和销毁,因此很难在策略类之外管理线程生命周期(启动/停止)。
我最终得到以下代码:
#include <iostream>
#include <cassert>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
struct Base
{
virtual ~Base()
{
std::cout << "In ~Base()" << std::endl;
// For testing purpose: spend some time in Base dtor
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
}
virtual void processEvents() = 0;
void startThread()
{
if(_thread)
{
stopThread();
}
_thread.reset(new boost::thread(&Base::processEvents, this));
assert(_thread);
}
void stopThread()
{
if(_thread)
{
std::cout << "Interrupting and joining thread" << std::endl;
_thread->interrupt();
_thread->join();
_thread.reset();
}
}
boost::shared_ptr<boost::thread> _thread;
};
struct Derived : public Base
{
Derived()
{
startThread();
}
virtual ~Derived()
{
std::cout << "In ~Derived()" << std::endl;
// For testing purpose: make sure the virtual method is called while in dtor
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
stopThread();
}
virtual void processEvents()
{
try
{
// Process events in Derived specific way
while(true)
{
// Emulated interruption point for testing purpose
boost::this_thread::sleep(boost::posix_time::milliseconds(100));
std::cout << "Processing events..." << std::endl;
}
}
catch (boost::thread_interrupted& e)
{
std::cout << "Thread interrupted" << std::endl;
}
}
};
int main(int argc, char** argv)
{
Base* b = new Derived;
delete b;
return 0;
}
如您所见,线程被中断并加入到Derived类析构函数中。许多关于 Stackoverflow 的评论认为,在析构函数中加入线程是个坏主意。但是,考虑到必须通过Derived类的构造/销毁来管理线程生命周期的约束,我找不到更好的主意。有人有更好的提议吗?