Jic*_*hao 1 c++ caching memory-management c++11
#include <mutex>
#include <assert.h>
#include <iostream>
#include <unordered_map>
#include <memory>
#include <string>
#include <stdio.h>
//
// Requirements:
// 1: the bitmap could be used by multiple thread safely.(std::shared_ptr could?)
// 2: cache the bitmap and do not always increase memeory
//@NotThreadSfe
struct Bitmap {
public:
Bitmap(const std::string& filePath) {
filePath_ = filePath;
printf("foo %x ctor %s\n", this, filePath_.c_str());
}
~Bitmap() {
printf("foo %x dtor %s\n", this, filePath_.c_str());
}
std::string filePath_;
};
//@ThreadSafe
struct BitmapCache {
public:
static std::shared_ptr<Bitmap> loadBitmap(const std::string& filePath) {
mutex_.lock();
//whether in the cache
auto iter = cache_.find(filePath);
if (iter != cache_.end()) {
if ((*iter).second) {
return (*iter).second;
} else {
std::shared_ptr<Bitmap> newPtr(new Bitmap(filePath));
(*iter).second = newPtr;
return newPtr;
}
}
//try remove unused elements if possible
if (cache_.size() >= kSlotThreshold) {
std::unordered_map<std::string,std::shared_ptr<Bitmap>>::iterator delIter = cache_.end();
for (auto iter = cache_.begin(); iter != cache_.end(); ++iter) {
auto& item = *iter;
if (item.second && item.second.use_count() == 1) {
delIter = iter;
break;
}
}
if (cache_.end() != delIter) {
(*delIter).second.reset();
cache_.erase(delIter);
}
}
//create new and insert to the cache
std::shared_ptr<Bitmap> newPtr(new Bitmap(filePath));
cache_.insert({filePath, newPtr});
mutex_.unlock();
return newPtr;
}
private:
static const int kSlotThreshold = 20;
static std::mutex mutex_;
static std::unordered_map<std::string,std::shared_ptr<Bitmap>> cache_;
};
/* static */
std::unordered_map<std::string,std::shared_ptr<Bitmap>> BitmapCache::cache_;
/* static */
std::mutex BitmapCache::mutex_;
int main()
{
//test for remove useless element
char buff[200] = {0};
std::vector<std::shared_ptr<Bitmap>> bmpVec(20);
for (int i = 0; i < 20; ++i) {
sprintf_s(buff, 200, "c:\\haha%d.bmp", i);
bmpVec[i] = BitmapCache::loadBitmap(buff);
}
bmpVec[3].reset();
std::shared_ptr<Bitmap> newBmp = BitmapCache::loadBitmap("c:\\new.bmp");
//test for multiple threading...(to be implemenetd)
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我是C++内存管理的新手.能不能给我一个提示:我是以正确的方式,还是应该采用不同的设计策略或不同的内存管理器策略(如weak_ptr等)?
T.C*_*.C. 17
这让我想起了Herb Sutter 在2013年GoingNative上的"最受欢迎的C++ 10-Liner"演讲,略有改编:
std::shared_ptr<Bitmap> get_bitmap(const std::string & path){
static std::map<std::string, std::weak_ptr<Bitmap>> cache;
static std::mutex m;
std::lock_guard<std::mutex> hold(m);
auto sp = cache[path].lock();
if(!sp) cache[path] = sp = std::make_shared<Bitmap>(path);
return sp;
}
Run Code Online (Sandbox Code Playgroud)
评论:
std::lock_guard而不是调用lock()和unlock()互斥.后者更容易出错,也不是例外安全.请注意,在您的代码中,前两个return语句从未解锁互斥锁.weak_ptr缓存内部分配的Bitmap对象,因此缓存永远不会使Bitmap自身保持活动状态.这样就不需要手动清理不再使用的对象 - 它们会在最后shared_ptr引用它们时被自动删除.path之前从未见过,或者相应的Bitmap已被删除,cache[path].lock()则返回空shared_ptr; 下面if的语句然后加载Bitmap用make_shared,移动,分配所产生的shared_ptr进入sp,并设置cache[path]来跟踪新创建位图.Bitmap对应path的仍然存活,那么cache[path].lock()将创建一个新的shared_ptr引用它,然后返回.| 归档时间: |
|
| 查看次数: |
2050 次 |
| 最近记录: |