1

My understanding is that all the Interlocked APIs in .NET will introduce a full memory fence. However, I still see many examples where volatile, which introduces half-fences, is used in conjunction with Interlocked. An example of that is Task.Id:

https://source.dot.net/#System.Private.CoreLib/Task.cs,784864bc4dc294af

        private volatile int m_taskId;

        public int Id
        {
            get
            {
                if (m_taskId == 0)
                {
                    int newId = NewId();
                    Interlocked.CompareExchange(ref m_taskId, newId, 0);
                }

                return m_taskId;
            }
        }

In instances like this, what is volatile actually doing?

4
  • 1
    volatile wouldn't appear to be doing anything in this particular case. Oct 26, 2020 at 20:23
  • Volatile does a couple of things: it ensures the compiler doesn't make optimizations that would interfere with the proper use of the variable; and, on some platforms, it will ensure that the value set in one thread is visible in another. Note that the Intel x86/x64 architecture implicitly addresses the latter goal, but this is not the case on every other platform. Oct 26, 2020 at 20:31
  • @PeterDuniho That makes sense, but don't interlocked operations ensure both of those things too? Or is that specific to the volatile keyword and the Volatile API? Oct 26, 2020 at 20:41
  • 1
    "don't interlocked operations ensure both of those things too?" -- no. Interlocked operations affect the sites in the code where the interlocked operations are actually done. The compiler has no way to know when optimizing code that uses a variable, whether that variable has been used in a call to an Interlocked method elsewhere or not. Similarly, a memory fence in one thread only affects reordering of read and/or write operations in that thread; you need another fence in other threads to do the same thing, otherwise the operations can still be reordered in a problematic way. Oct 26, 2020 at 22:05

0