Search code examples
c++multithreadingboost-threadthread-localthread-local-storage

How to release heap memory of thread local storage


I have a structure used for thread local storage like this:

namespace {
 typedef boost::unordered_map< std::string, std::vector<xxx> > YYY;
 boost::thread_specific_ptr<YYY> cache;

 void initCache() {
     //The first time called by the current thread.
     if (!cache.get()){
         cache.reset(new YYY());
     }
 }

void clearCache() {
     if (cache.get()){
         cache.reset();
     }
}
}

And a class whose object could have been created by the main thread:

class A {
public:
    void f() {
        initCache();
        //and for example:
        insertIntoCache();
    }
    ~A(){
        clearCache();// <-- Does/Can this do anything good ??
    }
}

Multiple threads can access object(s) of A stored, for example, in a global container. Each of these threads need to call A::f() from time to time. So they create their own copy of cache on the heap once , and finally join when they done with all their jobs.

So the question is : who is going to clean-up threads' memory? and How? Thank you


Solution

  • There's no reason to call clearCache().

    Once the thread exits or the thread_specific_ptr goes out of scope, the cleanup function will be invoked. If you don't pass a cleanup function to the thread_specific_ptr's constructor, it will just use delete.