samedi 26 mars 2016

Lock-free cache implementation in C++11

Is there any way in C++11 to implement a lock-free cache for an object, which would be safe to access from multiple threads? The calculation I'm looking to cache isn't super cheap but also isn't super expensive, so requiring a lock would defeat the purpose of caching in my case. IIUC, std::atomic isn't guaranteed to be lock-free.

Non-thread-safe cache example, just to demo the sort of cache I'm looking for:

class C {
public:
   C(int param) : m_param(param) {}

   getValue() {
      if (!alreadyCalculated) {
          m_val = calculate(m_param);
          alreadyCalculated = true;
      }
      return m_val;
   }

   double calculate(int param) {
       // Some calculation
   }

private:
   int m_param;
   double m_val;
   bool alreadyCalculated = false;
}

Aucun commentaire:

Enregistrer un commentaire