Interlocked Class

[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]

Provides atomic operations for variables that are shared by multiple threads.

Inheritance Hierarchy

System..::.Object
System.Threading..::.Interlocked

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

Syntax

Public NotInheritable Class Interlocked
public static class Interlocked

The Interlocked type exposes the following members.

Methods

Name Description
Add(Int32%, Int32) Adds two 32-bit integers and replaces the first integer with the sum, as an atomic operation.
Add(Int64%, Int64) Adds two 64-bit integers and replaces the first integer with the sum, as an atomic operation.
CompareExchange(Double%, Double, Double) Compares two double-precision floating point numbers for equality and, if they are equal, replaces one of the values.
CompareExchange(Int32%, Int32, Int32) Compares two 32-bit signed integers for equality and, if they are equal, replaces one of the values.
CompareExchange(Int64%, Int64, Int64) Compares two 64-bit signed integers for equality and, if they are equal, replaces one of the values.
CompareExchange(IntPtr%, IntPtr, IntPtr) Compares two platform-specific handles or pointers for equality and, if they are equal, replaces one of them.
CompareExchange(Object%, Object, Object) Compares two objects for reference equality and, if they are equal, replaces one of the objects.
CompareExchange(Single%, Single, Single) Compares two single-precision floating point numbers for equality and, if they are equal, replaces one of the values.
CompareExchange<(Of <(T>)>)(T%, T, T) Compares two instances of the specified reference type T for equality and, if they are equal, replaces one of them.
Decrement(Int32%) Decrements a specified 32-bit signed integer variable and stores the result, as an atomic operation.
Decrement(Int64%) Decrements the specified 64-bit signed integer variable and stores the result, as an atomic operation.
Exchange(Double%, Double) Sets a double-precision floating point number to a specified value and returns the original value, as an atomic operation.
Exchange(Int32%, Int32) Sets a 32-bit signed integer to a specified value and returns the original value, as an atomic operation.
Exchange(Int64%, Int64) Sets a 64-bit signed integer to a specified value and returns the original value, as an atomic operation.
Exchange(IntPtr%, IntPtr) Sets a platform-specific handle or pointer to a specified value and returns the original value, as an atomic operation.
Exchange(Object%, Object) Sets an object to a specified value and returns a reference to the original object, as an atomic operation.
Exchange(Single%, Single) Sets a single-precision floating point number to a specified value and returns the original value, as an atomic operation.
Exchange<(Of <(T>)>)(T%, T) Sets a variable of the specified type T to a specified value and returns the original value, as an atomic operation.
Increment(Int32%) Increments a specified 32-bit signed variable and stores the result, as an atomic operation.
Increment(Int64%) Increments a specified 64-bit signed integer variable and stores the result, as an atomic operation.
MemoryBarrier Synchronizes memory access as follows: The processor that executes the current thread cannot reorder instructions in such a way that memory accesses before the call to MemoryBarrier execute after memory accesses that follow the call to MemoryBarrier.
Read Returns a 64-bit value, loaded as an atomic operation.

Top

Remarks

The methods of this class help protect against errors that can occur when the scheduler switches contexts while a thread is updating a variable that can be accessed by other threads, or when two threads are executing concurrently on separate processors. The members of this class do not throw exceptions.

The Increment and Decrement methods increment or decrement a variable and store the resulting value in a single operation. On most computers, incrementing a variable is not an atomic operation. It requires the following steps:

  1. Load a value from an instance variable into a register.

  2. Increment or decrement the value.

  3. Store the value in the instance variable.

If you do not use Increment and Decrement, a thread can be preempted after executing the first two steps. Another thread can then execute all three steps. When the first thread resumes execution, it overwrites the value in the instance variable, and the effect of the increment or decrement performed by the second thread is lost.

The Exchange method atomically exchanges the values of the specified variables. The CompareExchange method combines two operations: It compares two values and stores a third value in one of the variables, based on the outcome of the comparison. The comparison and the exchange are performed as an atomic operation.

Version Notes

Windows Phone

64-bit members of the Interlocked class are present but not supported.

Examples

The following example shows a thread-safe resource locking mechanism.

Imports System.Threading

Class Example

    Private Shared outputBlock As System.Windows.Controls.TextBlock

    '0 for false, 1 for true.
    Private Shared usingResource As Integer = 0

    Private Const numThreadIterations As Integer = 5
    Private Const numThreads As Integer = 10

    Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)

        Example.outputBlock = outputBlock

        ' Run the demo on a separate thread because it uses Sleep, which makes
        ' the user interface unresponsive.
        Dim ct As New Thread(AddressOf ControlThread)
        ct.Start()

    End Sub

    Private Shared Sub ControlThread()

        Dim myThread As Thread
        Dim rnd As New Random()

        Dim i As Integer
        For i = 1 To numThreads 
            myThread = New Thread(AddressOf MyThreadProc)
            myThread.Name = [String].Format("Thread{0}", i)

            'Wait a random amount of time before starting next thread.
            Thread.Sleep(rnd.Next(0, 1000))
            myThread.Start()
        Next i
    End Sub 

    Private Shared Sub MyThreadProc()
        Dim i As Integer
        For i = 0 To numThreadIterations - 1
            UseResource()

            'Wait 1 second before next attempt.
            Thread.Sleep(1000)
        Next i
    End Sub 

    'A simple method that denies reentrancy.
    Shared Function UseResource() As Boolean
        '0 indicates that the method is not in use.
        If 0 = Interlocked.Exchange(usingResource, 1) Then
            Output(String.Format("{0} acquired the lock" & vbLf, Thread.CurrentThread.Name))

            'Code to access a resource that is not thread safe would go here.
            'Simulate some work
            Thread.Sleep(500)

            Output(String.Format("{0} exiting lock" & vbLf, Thread.CurrentThread.Name))

            'Release the lock
            Interlocked.Exchange(usingResource, 0)
            Return True
        Else
            Output(String.Format("   {0} was denied the lock" & vbLf, Thread.CurrentThread.Name))
            Return False
        End If
    End Function 

    ' Helper methods:

    ' In order to update the TextBlock object, which is on the UI thread, you must
    ' make a cross-thread call by using the Dispatcher object that is associated 
    ' with the TextBlock. The DisplayOutput helper method and its delegate, 
    ' displayHelper, are used by the BeginInvoke method of the Dispatcher object
    ' to append text to the TextBlock. 
    '
    Private Shared Sub Output(ByVal msg As String)
        outputBlock.Dispatcher.BeginInvoke(displayHelper, msg)
    End Sub
    Private Shared displayHelper As New Action(Of String)(AddressOf DisplayOutput)
    Private Shared Sub DisplayOutput(ByVal msg As String)
        outputBlock.Text &= msg 
    End Sub

End Class 

' This example produces output similar to the following:
'
'Thread1 acquired the lock
'   Thread2 was denied the lock
'Thread1 exiting lock 
'Thread3 acquired the lock
'   Thread4 was denied the lock
'   Thread2 was denied the lock
'   Thread1 was denied the lock
'Thread3 exiting lock 
'Thread6 acquired the lock
'   Thread7 was denied the lock
'   Thread4 was denied the lock
'   Thread2 was denied the lock
'   Thread5 was denied the lock
'Thread6 exiting lock 
'...
using System;
using System.Threading;

class Example
{
    private static System.Windows.Controls.TextBlock outputBlock;

    //0 for false, 1 for true.
    private static int usingResource = 0;

    private const int numThreadIterations = 5;
    private const int numThreads = 10;

    public static void Demo(System.Windows.Controls.TextBlock outputBlock)
    {
        Example.outputBlock = outputBlock;

        // Run the demo on a separate thread because it uses Sleep, which makes
        // the user interface unresponsive.
        Thread ct = new Thread(ControlThread);
        ct.Start();
    }

    private static void ControlThread()
    {
        Thread myThread;
        Random rnd = new Random();

        int i;
        for(i = 0; i < numThreads; i++)
        {
            myThread = new Thread(MyThreadProc);
            myThread.Name = String.Format("Thread{0}", i + 1);

            //Wait a random amount of time before starting next thread.
            Thread.Sleep(rnd.Next(0, 1000));
            myThread.Start();
        }
    }

    private static void MyThreadProc()
    {
        int i;
        for(i = 0; i < numThreadIterations; i++)
        {
            UseResource();

            //Wait 1 second before next attempt.
            Thread.Sleep(1000);
        }
    }

    //A simple method that denies reentrancy.
    public static bool UseResource()
    {
        //0 indicates that the method is not in use.
        if (0 == Interlocked.Exchange(ref usingResource, 1))
        {
            Output(String.Format("{0} acquired the lock\n", Thread.CurrentThread.Name));

            //Code to access a resource that is not thread safe would go here.
            //Simulate some work
            Thread.Sleep(500);

            Output(String.Format("{0} exiting lock\n", Thread.CurrentThread.Name));

            //Release the lock
            Interlocked.Exchange(ref usingResource, 0);
            return true;
        }
        else
        {
            Output(String.Format("   {0} was denied the lock\n", Thread.CurrentThread.Name));
            return false;
        }
    }

    // Helper methods:

    // In order to update the TextBlock object, which is on the UI thread, you must
    // make a cross-thread call by using the Dispatcher object that is associated 
    // with the TextBlock. The DisplayOutput helper method and its delegate, 
    // displayHelper, are used by the BeginInvoke method of the Dispatcher object
    // to append text to the TextBlock. 
    //
    private static void Output(string msg)
    {
        outputBlock.Dispatcher.BeginInvoke(displayHelper, msg);
    }
    private static Action<string> displayHelper = new Action<string>(DisplayOutput);
    private static void DisplayOutput(string msg)
    {
        outputBlock.Text += msg;
    }
}

/* This example produces output similar to the following:

Thread1 acquired the lock
   Thread2 was denied the lock
Thread1 exiting lock 
Thread3 acquired the lock
   Thread4 was denied the lock
   Thread2 was denied the lock
   Thread1 was denied the lock
Thread3 exiting lock 
Thread6 acquired the lock
   Thread7 was denied the lock
   Thread4 was denied the lock
   Thread2 was denied the lock
   Thread5 was denied the lock
Thread6 exiting lock 
...
 */

Version Information

Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Platforms

Windows Phone

Thread Safety

This type is thread safe.

See Also

Reference

System.Threading Namespace

Other Resources

Managed Threading

Interlocked Operations