Consider the following code (part of a class):
void MyClass::foo() {
//...
mutex_.lock();
if (state_ == first) {
mutex_.unlock();
thread_ = boost::shared_ptr<boost::thread>(new boost::thread(boost::bind(&MyClass::bar, this)))
}
mutex_.unlock();
//...
}
void MyClass::bar() {
//...
while (true) {
//...
mutex_.lock();
if (state_ == last) {
mutex_.unlock();
state_ = first;
break;
}
mutex_.unlock();
//...
}
}
This code makes sure that whenever thread_
is assigned to point to a new thread, the previous thread will have already finished (or, in the first time, have not been started at all).
Is this code safe from memory leaks/are there things I've missed? I am not sure whether a thread which has finished needs to be deallocated with delete
.