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

标签 c++ static thread-safety mutable

我有一个相对昂贵的数据获取操作,我想缓存其结果。此操作调用自 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/

相关文章:

python - C++ - 读取 16 位 .wav 文件

c++ - 静态计数器-如何让ID不改变[C++]

multithreading - 在Grails(1.3.6) Controller 操作和类变量线程下声明的变量安全吗?

c++ - QList、QVector 或 std::vector 多线程使用

c++ - 除了类(class)以外的所有人都是常数,有这样的事情吗?

c++ - 带有元数据的 Lua 回调

c# - 如何在 parent 静态方法中使用 child 的变量?

multithreading - delphi中的线程安全

c++ - 过滤掉仅匹配字典中单词的排列

动态仪器与静态仪器