title: Lock-free cache implementation in C++11
body: <p>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, <code>std::atomic</code> isn't guaranteed to be lock-free.</p>
  
  <p>Edit: Since calculate isn't -too- expensive, I actually don't mind if it runs once or twice too many. But I -do- need to make sure all consumers get the correct value. In the naive example below, this isn't guaranteed because due to memory re-ordering it's possible for a thread to get an uninitialized value of <code>m_val</code> since another thread set <code>m_alreadyCalculated</code> to true, but didn't set <code>m_val</code>'s value yet.</p>
  
  <p>Edit2: The comments below point out that for basic types, <code>std::atomic</code> would probably be lock free. In case it is, what's the correct way in the example below of using C++11's memory ordering to make sure it isn't possible for <code>m_alreadyCalculated</code> to be set to true before <code>m_val</code>'s value is set?</p>
  
  <p>Non-thread-safe cache example:</p>
  
  <pre><code>class C {
  public:
     C(int param) : m_param(param) {}
  
     getValue() {
        if (!m_alreadyCalculated) {
            m_val = calculate(m_param);
            m_alreadyCalculated = true;
        }
        return m_val;
     }
  
     double calculate(int param) {
         // Some calculation
     }
  
  private:
     int m_param;
     double m_val;
     bool m_alreadyCalculated = false;
  }
  </code></pre>