我想寫一個類,它將在其對象創建時運行一個線程,並在對象被刪除後停止線程。刪除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