C++ 如何释放线程本地存储的堆内存
我有一个用于线程本地存储的结构,如下所示:C++ 如何释放线程本地存储的堆内存,c++,multithreading,boost-thread,thread-local,thread-local-storage,C++,Multithreading,Boost Thread,Thread Local,Thread Local Storage,我有一个用于线程本地存储的结构,如下所示: 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.g
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();
}
}
}
多个线程可以访问存储在全局容器中的A
的对象。每个线程都需要不时调用A::f()
。因此,他们在堆上创建自己的缓存
副本一次,最后在完成所有作业后加入
所以问题是:谁来清理线程的内存?怎么做?
谢谢没有理由调用clearCache()
一旦线程退出或线程特定的\u ptr
超出范围,将调用清理功能。如果您不将清理函数传递给特定于线程的ptr
的构造函数,它将只使用删除
我明白了,请您提供一个参考以供更多阅读。感谢阅读thread\u specific\u ptr
class A {
public:
void f() {
initCache();
//and for example:
insertIntoCache();
}
~A(){
clearCache();// <-- Does/Can this do anything good ??
}
}