在C ++中缓存昂贵的数据-函数范围的静态变量与可变成员变量 [英] Caching expensive data in C++ - function-scoped statics vs mutable member variables
问题描述
我有一个相对昂贵的数据获取操作,我想缓存结果.从const
方法调用此操作,大致如下:
I've got a relatively expensive data-fetching operation that I want to cache the results of. This operation is called from const
methods, roughly like this:
double AdjustData(double d, int key) const {
double factor = LongRunningOperationToFetchFactor(key);
return factor * d;
}
我希望AdjustData
保持为const
,但是我想缓存该因子,因此我仅在第一次提取它.目前,我正在使用mutable map<int, double>
存储结果(映射从key
到factor
),但是我认为使用函数范围的静态可能是更好的解决方案-仅需要此因子通过此功能,与课程的其余部分无关.
I'd like AdjustData
to remain const
, but I want to cache out the factor so I only fetch it the first time. At present I'm using a mutable map<int, double>
to store the result (the map being from key
to factor
), but I'm thinking using a function-scoped static might be a better solution - this factor is only needed by this function, and is irrelevant to the rest of the class.
这似乎是个好方法吗?有没有更好的选择?我可能会想些什么,尤其是关于线程安全性.
Does that seem like a good way to go? Are there any better options? What things might I think about, particularly with regard to thread-safety.
谢谢
Dom
推荐答案
我将使用以下方法包装LongRunningOperationToFetchFactor的实现.我正在使用Boost范围锁,但是您可以使用与其他锁框架类似的东西.
I would wrap the implementation of LongRunningOperationToFetchFactor with something like this. I am using Boost scoped locks but you can so something similar with other locking frameworks.
#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;
}
如果这确实是一个长期运行的操作,那么锁定Mutex的成本应该是最小的.
If this really is a long running operation then the cost of locking the Mutex should be minimal.
您的问题还不清楚,但是如果函数LongRunningOperationToFetchFactor是您的类的成员函数,那么您希望该映射是同一类中的可变映射.我仍然可以使用单个静态互斥锁进行访问,但是仍然足够快.
It was not quite clear from you question but if the function LongRunningOperationToFetchFactor is a member function of you class then you want the map the be mutable map in that same class. I single static mutex for access is still fast enough though.
这篇关于在C ++中缓存昂贵的数据-函数范围的静态变量与可变成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!