Imports System.Threading

Namespace Threading

    ''' <summary>
    ''' Exposes volatile read/write methods.
    ''' </summary>
    ''' <remarks></remarks>
    Public Class Volatile

        ''' <summary>
        ''' Reads the value of a field. The value is the latest written by any 
        ''' processor in a computer, regardless of the number of processors or 
        ''' the state of processor cache.
        ''' </summary>
        ''' <typeparam name="T">The type of the value to read.</typeparam>
        ''' <param name="address">The field to be read.</param>
        ''' <returns>The latest value (written by any processor) on the field.</returns>
        ''' <remarks></remarks>
        Public Shared Function VolatileRead(Of T)(ByRef address As T) As T
            Dim result As T = address
            Thread.MemoryBarrier()
            Return result
        End Function

        ''' <summary>
        ''' Writes a value to a field immediately, so that the value is visible to all processors in the computer.
        ''' </summary>
        ''' <typeparam name="T">The type of the value to write.</typeparam>
        ''' <param name="address">The field to which the value is to be written.</param>
        ''' <param name="value">The value to be written.</param>
        ''' <remarks></remarks>
        Public Shared Sub VolatileWrite(Of T)(ByRef address As T, ByVal value As T)
            Thread.MemoryBarrier()
            address = value
        End Sub

    End Class

End Namespace