gpt4 book ai didi

c++ - 在 C++ 中缓存昂贵的数据——函数范围的静态变量与可变成员变量

转载 作者:可可西里 更新时间:2023-11-01 16:37:56 26 4
gpt4 key购买 nike

我有一个相对昂贵的数据获取操作,我想缓存其结果。此操作调用自 const方法,大致是这样的:

double AdjustData(double d, int key) const {
double factor = LongRunningOperationToFetchFactor(key);
return factor * d;
}

我想要AdjustData留下来const ,但我想缓存这个因素,所以我只在第一次获取它。目前我正在使用 mutable map<int, double>存储结果( map 从 keyfactor ),但我认为使用函数范围的静态可能是更好的解决方案 - 这个因素只需要这个函数,并且与其余部分无关类(class)的。

这看起来是个好方法吗?有没有更好的选择?我可能会考虑哪些事情,尤其是在线程安全方面。

谢谢,

主场

最佳答案

我会用类似这样的东西包装 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;
}

如果这确实是一个长时间运行的操作,那么锁定 Mutex 的成本应该是最小的。

你的问题不是很清楚,但如果函数 LongRunningOperationToFetchFactor 是你类的成员函数,那么你希望映射是同一个类中的可变映射。不过,我使用单个静态互斥锁进行访问仍然足够快。

关于c++ - 在 C++ 中缓存昂贵的数据——函数范围的静态变量与可变成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/614875/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com