我想写一个类,它将在其对象创建时运行一个线程,并在对象被删除后停止线程。删除boost ::线程后裔
class MyThread : public boost::thread {
public:
MyThread() : bAlive(true) {
boost::thread(&MyThread::ThreadFunction,this);
}
~MyThread() {
{
boost::unique_lock<boost::mutex> lock(Mutex);
bAlive=false;
}
ConditionVariable.notify_one();
join();
}
private:
volatile bool bAlive;
boost::mutex Mutex;
boost::condition_variable ConditionVariable;
void ThreadFunction() {
boost::unique_lock<boost::mutex> lock(Mutex);
while(bAlive) {
ConditionVariable.timed_wait(lock,boost::get_system_time()+ boost::posix_time::milliseconds(MAX_IDLE));
/*******************************************
* Here goes some code executed by a thread *
*******************************************/
}
}
};
从理论上讲,我想马上尽快唤醒线程了,因为它需要完成,所以我只好用TIMED_WAIT而不是睡眠。 这工作正常,直到我尝试删除此类的一个对象。在大多数情况下,它会正常删除,但偶尔它会在condition_variable.hpp,thread_primitives.hpp或crtexe.c中导致错误。有时我会收到通知:“释放后在3da804中修改了自由堆3da7a8”,有时候我没有。是的,我知道timed_wait的虚假唤醒,在这种情况下并不重要。 你能指点我的问题来源吗?我究竟做错了什么?
不太清楚的问题是什么,有没有问号在这个问题 – jcw