zzy zzy - 1 year ago 56
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 {
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

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;

After timeout, I will delete this
pointer. Here will be a problem, the
hasn't return, it will have chances to access
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
is valid or member variables is valid ? Or could I set some flags to tell
the destructor has been called ?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download