我有一个相对昂贵的数据获取操作,我想缓存其结果。这个操作是从调用的const
方法,大致是这样的:
double AdjustData(double d, int key) const {
double factor = LongRunningOperationToFetchFactor(key);
return factor * d;
}
我想要AdjustData
保持const
,但我想缓存这个因素,所以我只在第一次获取它。目前我正在使用mutable map<int, double>
存储结果(地图来自key
to factor
),但我认为使用函数范围的静态可能是一个更好的解决方案 - 这个因素仅由该函数需要,并且与类的其余部分无关。
这看起来是个好方法吗?还有更好的选择吗?我可能会考虑哪些事情,特别是在线程安全方面。
Thanks,
Dom
我会用这样的东西包装 LongRunningOperationToFetchFactor 的实现。我正在使用 Boost 作用域锁,但您也可以使用其他锁定框架进行类似的操作。
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <map>
using namespace std;
static boost::mutex myMutex;
static map<int,double> results;
double CachedLongRunningOperationToFetchFactor( int key )
{
{
boost::mutex::scoped_lock lock(myMutex);
map<int,double>::iterator iter = results.find(key);
if ( iter != results.end() )
{
return (*iter).second;
}
}
// not in the Cache calculate it
result = LongRunningOperationToFetchFactor( key );
{
// we need to lock the map again
boost::mutex::scoped_lock lock(myMutex);
// it could be that another thread already calculated the result but
// map assignment does not care.
results[key] = result;
}
return result;
}
如果这确实是一个长时间运行的操作,那么锁定互斥体的成本应该是最小的。
您的问题不太清楚,但如果函数 LongRunningOperationToFetchFactor 是您类的成员函数,那么您希望该映射在同一类中成为可变映射。不过,我使用单个静态互斥体进行访问仍然足够快。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)