Search code examples
c++visual-studio-2010volatile

Access method for volatile members


We have a wrapper that represents an atomic integer. Internally, it is implemented using Windows' InterlockedIncrement() and InterlockedDecrement() functions, which work on a volatile long variable:

class AtomicInt {
public:
    ...

    operator long() const { return m_value; }

private:
    volatile long m_value;
};

My question is, is the above operator for querying the current value correct (i.e. you always get the current value) or do I need to declare the method also as volatile to prevent any problems with cached values?


Solution

  • What you've done is fine ... you don't need to mark the method as volatile. Also since you've included the definition of the method in the class declaration, the method will typically be implicitly inlined by the compiler, so the actual function call mechanism would be elided during the compiler optimization process. Thus in most contexts, the variable itself would be accessed directly without an intervening function call, making the volatile declaration on the variable enough.

    BTW, for future reference, keep in mind that in a multi-processor environment outside of x86, the volatile keyword is not enough to ensure that a thread using your shared memory value not receive cached data. The volatile keyword in general merely prevents certain compiler optimizations. On processor platforms with weaker memory consistency rules (i.e., ARM, PowerPC, etc.) though, you can still end up accessing a cached value from the local processor core even if the variable is marked as volatile. The way around this is to implement the proper memory barriers to make sure that any stale values in the actual processor memory caches are flushed and refreshed. These are of course platform-dependent instructions ... the good news in your case is the compiler intrinsics you're using will assure that your don't face these issues with your AtomicInt class, but I did want to make you aware of this general issue surrounding the volatile keyword.