zzy zzy - 3 months ago 9
C++ Question

How to check destructor has been called in thread?

I'm using boost to start a thread and the thread function is a member function of my class just like this:

class MyClass {
public:
void ThreadFunc();
void StartThread() {
worker_thread_ = boost::shared_ptr<boost::thread>(
new boost::thread(boost::bind(&MyClass::ThreadFunc, this)));
}
};


I will access some member variables in
ThreadFunc
:

while (!stop) {
Sleep(1000); // here will be some block operations
auto it = this->list.begin();
if (it != this->list.end())
...
}


I can not wait forever for thread return, so I set timeout:

stop = true;
worker_thread_->interrupt();
worker_thread_->timed_join(boost::posix_time::milliseconds(timeout_ms));


After timeout, I will delete this
MyClass
pointer. Here will be a problem, the
ThreadFunc
hasn't return, it will have chances to access
this
and its member variables. In my case, the iterator will be invalid and
it != this->list.end()
will be true, so my program will crash if using invalid iterator.

My question is how to avoid it ? Or how to check whether
this
is valid or member variables is valid ? Or could I set some flags to tell
ThreadFunc
the destructor has been called ?

Answer

There are a lot of possible solutions. One is to use a shared_ptr to the class and let the thread hold its own shared_ptr to the class. That way, the object will automatically get destroyed only when both threads are done with it.