Interlocked.CompareExchange Method (Single, Single, Single)


Compares two single-precision floating point numbers for equality and, if they are equal, replaces the first value.

Namespace:   System.Threading
Assembly:  mscorlib (in mscorlib.dll)

Public Shared Function CompareExchange (
	ByRef location1 As Single,
	value As Single,
	comparand As Single
) As Single


Type: System.Single

The destination, whose value is compared with comparand and possibly replaced.

Type: System.Single

The value that replaces the destination value if the comparison results in equality.

Type: System.Single

The value that is compared to the value at location1.

Return Value

Type: System.Single

The original value in location1.

Exception Condition

The address of location1 is a null pointer.

If comparand and the value in location1 are equal, then value is stored in location1. Otherwise, no operation is performed. The compare and exchange operations are performed as an atomic operation. The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.

The following code example demonstrates a thread-safe method that accumulates a running total of Single values. Two threads add a series of Single values using the thread-safe method and ordinary addition, and when the threads complete the totals are compared. On a dual-processor computer, there is a significant difference in the totals.

In the thread-safe method, the initial value of the running total is saved, and then the CompareExchange method is used to exchange the newly computed total with the old total. If the return value is not equal to the saved value of the running total, then another thread has updated the total in the meantime. In that case, the attempt to update the running total must be repeated.

' This example demonstrates a thread-safe method that adds to a
' running total.  
Imports System.Threading

Public Class ThreadSafe
    ' Field totalValue contains a running total that can be updated
    ' by multiple threads. It must be protected from unsynchronized 
    ' access.
    Private totalValue As Single = 0.0

    ' The Total property returns the running total.
    Public ReadOnly Property Total As Single
            Return totalValue
        End Get
    End Property

    ' AddToTotal safely adds a value to the running total.
    Public Function AddToTotal(ByVal addend As Single) As Single
        Dim initialValue, computedValue As Single
            ' Save the current running total in a local variable.
            initialValue = totalValue

            ' Add the new value to the running total.
            computedValue = initialValue + addend

            ' CompareExchange compares totalValue to initialValue. If
            ' they are not equal, then another thread has updated the
            ' running total since this loop started. CompareExchange
            ' does not update totalValue. CompareExchange returns the
            ' contents of totalValue, which do not equal initialValue,
            ' so the loop executes again.
        Loop While initialValue <> Interlocked.CompareExchange( _
            totalValue, computedValue, initialValue)
        ' If no other thread updated the running total, then 
        ' totalValue and initialValue are equal when CompareExchange
        ' compares them, and computedValue is stored in totalValue.
        ' CompareExchange returns the value that was in totalValue
        ' before the update, which is equal to initialValue, so the 
        ' loop ends.

        ' The function returns computedValue, not totalValue, because
        ' totalValue could be changed by another thread between
        ' the time the loop ends and the function returns.
        Return computedValue
    End Function
End Class

Public Class Test
    ' Create an instance of the ThreadSafe class to test.
    Private Shared ts As New ThreadSafe()
    Private Shared control As Single

    Private Shared r As New Random()
    Private Shared mre As New ManualResetEvent(false)

    <MTAThread> _
    Public Shared Sub Main()
        ' Create two threads, name them, and start them. The
        ' threads will block on mre.
        Dim t1 As New Thread(AddressOf TestThread)
        t1.Name = "Thread 1"
        Dim t2 As New Thread(AddressOf TestThread)
        t2.Name = "Thread 2"

        ' Now let the threads begin adding random numbers to 
        ' the total.

        ' Wait until all the threads are done.

        Console.WriteLine("Thread safe: {0}  Ordinary Single: {1}", ts.Total, control)
    End Sub

    Private Shared Sub TestThread()
        ' Wait until the signal.

        For i As Integer = 1 to 1000000
            ' Add to the running total in the ThreadSafe instance, and
            ' to an ordinary Single.
            Dim testValue As Single = r.NextDouble()
            control += testValue
    End Sub
End Class

' On a dual-processor computer, this code example produces output 
' similar to the following:
'Thread safe: 17039.57  Ordinary Single: 15706.44

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Windows Phone Silverlight
Available since 8.0
Windows Phone
Available since 8.1
Return to top