0

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.

space_voyager
  • 1,984
  • 3
  • 20
  • 31
  • 1
    Wouldn't `boost::shared_ptr` take care of deallocation for you? – Charles May 12 '17 at 00:42
  • I don't know enough about boost::shared_ptr to be able to say that with certainty. – space_voyager May 12 '17 at 00:49
  • 1. Anything ***absolutely anything*** (including threads) you allocate with `new` should be deallocated with with `delete`. It's your responsibility to ensure this happens. (How you _ensure_ it, is up to you.) 2. One technique to ensure something is deallocated is to assign it to an appropriate [smart pointer](https://en.wikipedia.org/wiki/Smart_pointer). E.g. A shared point is "reference-counted" meaning a count of the total number references to the same instance is automatically maintained. When the last reference is reassigned or goes out of scope, the object is `delete`d automatically. – Disillusioned May 12 '17 at 01:23
  • Possible duplicate of [What is a smart pointer and when should I use one?](http://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one) – Disillusioned May 12 '17 at 01:24
  • @CraigYoung So for my case, the answer would be that I do not need to call delete myself since it will happen automatically when `thread_` is reassigned to point to a different thread? – space_voyager May 12 '17 at 01:28

0 Answers0