Interlocked Class

Definition

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

public ref class Interlocked abstract sealed
public ref class Interlocked sealed
public static class Interlocked
public sealed class Interlocked
type Interlocked = class
Public Class Interlocked
Public NotInheritable Class Interlocked
Inheritance
Interlocked

Examples

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

using namespace System;
using namespace System::Threading;

const int numThreads = 10;
const int numThreadIterations = 5;
ref class MyInterlockedExchangeExampleClass
{
public:
   static void MyThreadProc()
   {
      for ( int i = 0; i < numThreadIterations; i++ )
      {
         UseResource();
         
         //Wait 1 second before next attempt.
         Thread::Sleep( 1000 );

      }
   }


private:
   //A simple method that denies reentrancy.
   static bool UseResource()
   {
      
      //0 indicates that the method is not in use.
      if ( 0 == Interlocked::Exchange( usingResource, 1 ) )
      {
         Console::WriteLine( " {0} acquired the lock", Thread::CurrentThread->Name );
         
         //Code to access a resource that is not thread safe would go here.
         //Simulate some work
         Thread::Sleep( 500 );
         Console::WriteLine( " {0} exiting lock", Thread::CurrentThread->Name );
         
         //Release the lock
         Interlocked::Exchange( usingResource, 0 );
         return true;
      }
      else
      {
         Console::WriteLine( " {0} was denied the lock", Thread::CurrentThread->Name );
         return false;
      }
   }


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

int main()
{
   Thread^ myThread;
   Random^ rnd = gcnew Random;
   for ( int i = 0; i < numThreads; i++ )
   {
      myThread = gcnew Thread( gcnew ThreadStart( MyInterlockedExchangeExampleClass::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();

   }
}
using System;
using System.Threading;

namespace InterlockedExchange_Example
{
    class MyInterlockedExchangeExampleClass
    {
        //0 for false, 1 for true.
        private static int usingResource = 0;

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

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

            for(int i = 0; i < numThreads; i++)
            {
                myThread = new Thread(new ThreadStart(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()
        {
            for(int i = 0; i < numThreadIterations; i++)
            {
                UseResource();
            
                //Wait 1 second before next attempt.
                Thread.Sleep(1000);
            }
        }

        //A simple method that denies reentrancy.
        static bool UseResource()
        {
            //0 indicates that the method is not in use.
            if(0 == Interlocked.Exchange(ref usingResource, 1))
            {
                Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name);
            
                //Code to access a resource that is not thread safe would go here.
            
                //Simulate some work
                Thread.Sleep(500);

                Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name);
            
                //Release the lock
                Interlocked.Exchange(ref usingResource, 0);
                return true;
            }
            else
            {
                Console.WriteLine("   {0} was denied the lock", Thread.CurrentThread.Name);
                return false;
            }
        }
    }
}
Imports System.Threading

Namespace InterlockedExchange_Example
    Class MyInterlockedExchangeExampleClass
        '0 for false, 1 for true.
        Private Shared usingResource As Integer = 0

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

        <MTAThread> _
        Shared Sub Main()
            Dim myThread As Thread
            Dim rnd As New Random()

            Dim i As Integer
            For i = 0 To numThreads - 1
                myThread = New Thread(AddressOf 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()
            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
                Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name)

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

                Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name)

                'Release the lock
                Interlocked.Exchange(usingResource, 0)
                Return True
            Else
                Console.WriteLine("   {0} was denied the lock", Thread.CurrentThread.Name)
                Return False
            End If
        End Function 
    End Class 
End Namespace

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, requiring 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 Add method atomically adds an integer value to an integer variable and returns the new value of the variable.

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

Ensure that any write or read access to a shared variable is atomic. Otherwise, the data might be corrupted or the loaded value might be incorrect.

Methods

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.

Add(UInt32, UInt32)

Adds two 32-bit unsigned integers and replaces the first integer with the sum, as an atomic operation.

Add(UInt64, UInt64)

Adds two 64-bit unsigned integers and replaces the first integer with the sum, as an atomic operation.

And(Int32, Int32)

Bitwise "ands" two 32-bit signed integers and replaces the first integer with the result, as an atomic operation.

And(Int64, Int64)

Bitwise "ands" two 64-bit signed integers and replaces the first integer with the result, as an atomic operation.

And(UInt32, UInt32)

Bitwise "ands" two 32-bit unsigned integers and replaces the first integer with the result, as an atomic operation.

And(UInt64, UInt64)

Bitwise "ands" two 64-bit unsigned integers and replaces the first integer with the result, as an atomic operation.

CompareExchange(Byte, Byte, Byte)
CompareExchange(Double, Double, Double)

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

CompareExchange(Int16, Int16, Int16)
CompareExchange(Int32, Int32, Int32)

Compares two 32-bit signed integers for equality and, if they are equal, replaces the first value.

CompareExchange(Int64, Int64, Int64)

Compares two 64-bit signed integers for equality and, if they are equal, replaces the first value.

CompareExchange(IntPtr, IntPtr, IntPtr)

Compares two platform-specific handles or pointers for equality and, if they are equal, replaces the first one.

CompareExchange(Object, Object, Object)

Compares two objects for reference equality and, if they are equal, replaces the first object.

CompareExchange(SByte, SByte, SByte)
CompareExchange(Single, Single, Single)

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

CompareExchange(UInt16, UInt16, UInt16)
CompareExchange(UInt32, UInt32, UInt32)

Compares two 32-bit unsigned integers for equality and, if they are equal, replaces the first value.

CompareExchange(UInt64, UInt64, UInt64)

Compares two 64-bit unsigned integers for equality and, if they are equal, replaces the first value.

CompareExchange(UIntPtr, UIntPtr, UIntPtr)

Compares two platform-specific handles or pointers for equality and, if they are equal, replaces the first one.

CompareExchange<T>(T, T, T)

Compares two instances of the specified reference type T for reference equality and, if they are equal, replaces the first one.

Decrement(Int32)

Decrements a specified variable and stores the result, as an atomic operation.

Decrement(Int64)

Decrements the specified variable and stores the result, as an atomic operation.

Decrement(UInt32)

Decrements a specified variable and stores the result, as an atomic operation.

Decrement(UInt64)

Decrements a specified variable and stores the result, as an atomic operation.

Exchange(Byte, Byte)
Exchange(Double, Double)

Sets a double-precision floating point number to a specified value and returns the original value, as an atomic operation.

Exchange(Int16, Int16)
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(SByte, SByte)
Exchange(Single, Single)

Sets a single-precision floating point number to a specified value and returns the original value, as an atomic operation.

Exchange(UInt16, UInt16)
Exchange(UInt32, UInt32)

Sets a 32-bit unsigned integer to a specified value and returns the original value, as an atomic operation.

Exchange(UInt64, UInt64)

Sets a 64-bit unsigned integer to a specified value and returns the original value, as an atomic operation.

Exchange(UIntPtr, UIntPtr)

Sets a platform-specific handle or pointer to a specified value and returns the original value, as an atomic operation.

Exchange<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 variable and stores the result, as an atomic operation.

Increment(Int64)

Increments a specified variable and stores the result, as an atomic operation.

Increment(UInt32)

Increments a specified variable and stores the result, as an atomic operation.

Increment(UInt64)

Increments a specified 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().

MemoryBarrierProcessWide()

Provides a process-wide memory barrier that ensures that reads and writes from any CPU cannot move across the barrier.

Or(Int32, Int32)

Bitwise "ors" two 32-bit signed integers and replaces the first integer with the result, as an atomic operation.

Or(Int64, Int64)

Bitwise "ors" two 64-bit signed integers and replaces the first integer with the result, as an atomic operation.

Or(UInt32, UInt32)

Bitwise "ors" two 32-bit unsigned integers and replaces the first integer with the result, as an atomic operation.

Or(UInt64, UInt64)

Bitwise "ors" two 64-bit unsigned integers and replaces the first integer with the result, as an atomic operation.

Read(Int64)

Returns a 64-bit value, loaded as an atomic operation.

Read(UInt64)

Returns a 64-bit unsigned value, loaded as an atomic operation.

SpeculationBarrier()

Defines a memory fence that blocks speculative execution past this point until pending reads and writes are complete.

Applies to

Thread Safety

This type is thread safe.

See also