Interlocked Interlocked Interlocked Interlocked Class

定义

为多个线程共享的变量提供原子操作。Provides atomic operations for variables that are shared by multiple threads.

public ref class Interlocked abstract sealed
public static class Interlocked
type Interlocked = class
Public Class Interlocked
继承
InterlockedInterlockedInterlockedInterlocked

示例

下面的代码示例演示线程安全资源锁定机制。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
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 'Main

        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 

注解

此类的方法可帮助防止在以下情况下发生的错误: 在以下情况下发生: 计划程序在以下情况下切换上下文: 当线程正在更新可被其他线程访问的变量时, 或当两个线程同时在不同的处理器上执行时。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.

IncrementDecrement方法递增或递减变量, 并在单个操作中存储生成的值。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.

如果不使用IncrementDecrement, 则在执行前两个步骤后, 线程可以被抢占。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.

Add方法以原子方式将整数值添加到整数变量中, 并返回变量的新值。The Add method atomically adds an integer value to an integer variable and returns the new value of the variable.

Exchange方法以原子方式交换指定变量的值。The Exchange method atomically exchanges the values of the specified variables. CompareExchange方法组合了两个操作: 比较两个值, 并根据比较结果将第三个值存储在一个变量中。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.

方法

Add(Int32, Int32) Add(Int32, Int32) Add(Int32, Int32) Add(Int32, Int32)

对两个 32 位整数进行求和并用和替换第一个整数,上述操作作为一个原子操作完成。Adds two 32-bit integers and replaces the first integer with the sum, as an atomic operation.

Add(Int64, Int64) Add(Int64, Int64) Add(Int64, Int64) Add(Int64, Int64)

对两个 64 位整数进行求和并用和替换第一个整数,上述操作作为一个原子操作完成。Adds two 64-bit integers and replaces the first integer with the sum, as an atomic operation.

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

比较两个双精度浮点数是否相等,如果相等,则替换第一个值。Compares two double-precision floating point numbers for equality and, if they are equal, replaces the first value.

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

比较两个 32 位有符号整数是否相等,如果相等,则替换第一个值。Compares two 32-bit signed integers for equality and, if they are equal, replaces the first value.

CompareExchange(Int64, Int64, Int64) CompareExchange(Int64, Int64, Int64) CompareExchange(Int64, Int64, Int64) CompareExchange(Int64, Int64, Int64)

比较两个 64 位有符号整数是否相等,如果相等,则替换第一个值。Compares two 64-bit signed integers for equality and, if they are equal, replaces the first value.

CompareExchange(IntPtr, IntPtr, IntPtr) CompareExchange(IntPtr, IntPtr, IntPtr) CompareExchange(IntPtr, IntPtr, IntPtr) 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) CompareExchange(Object, Object, Object) CompareExchange(Object, Object, Object) CompareExchange(Object, Object, Object)

比较两个对象是否引用相等,如果相等,则替换第一个对象。Compares two objects for reference equality and, if they are equal, replaces the first object.

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

比较两个单精度浮点数是否相等,如果相等,则替换第一个值。Compares two single-precision floating point numbers for equality and, if they are equal, replaces the first value.

CompareExchange<T>(T, T, T) CompareExchange<T>(T, T, T) CompareExchange<T>(T, T, T) CompareExchange<T>(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) Decrement(Int32) Decrement(Int32) Decrement(Int32)

以原子操作的形式递减指定变量的值并存储结果。Decrements a specified variable and stores the result, as an atomic operation.

Decrement(Int64) Decrement(Int64) Decrement(Int64) Decrement(Int64)

以原子操作的形式递减指定变量的值并存储结果。Decrements the specified variable and stores the result, as an atomic operation.

Exchange(Single, Single) Exchange(Single, Single) Exchange(Single, Single) Exchange(Single, Single)

以原子操作的形式,将单精度浮点数设置为指定的值并返回原始值。Sets a single-precision floating point number to a specified value and returns the original value, as an atomic operation.

Exchange(Object, Object) Exchange(Object, Object) Exchange(Object, Object) Exchange(Object, Object)

以原子操作的形式,将对象设置为指定的值并返回对原始对象的引用。Sets an object to a specified value and returns a reference to the original object, as an atomic operation.

Exchange(IntPtr, IntPtr) Exchange(IntPtr, IntPtr) Exchange(IntPtr, IntPtr) Exchange(IntPtr, IntPtr)

以原子操作的形式,将平台特定的句柄或指针设置为指定的值并返回原始值。Sets a platform-specific handle or pointer to a specified value and returns the original value, as an atomic operation.

Exchange(Double, Double) Exchange(Double, Double) Exchange(Double, Double) 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) Exchange(Int32, Int32) Exchange(Int32, Int32) Exchange(Int32, Int32)

以原子操作的形式,将 32 位有符号整数设置为指定的值并返回原始值。Sets a 32-bit signed integer to a specified value and returns the original value, as an atomic operation.

Exchange(Int64, Int64) Exchange(Int64, Int64) Exchange(Int64, Int64) Exchange(Int64, Int64)

以原子操作的形式,将 64 位有符号整数设置为指定的值并返回原始值。Sets a 64-bit signed integer to a specified value and returns the original value, as an atomic operation.

Exchange<T>(T, T) Exchange<T>(T, T) Exchange<T>(T, T) Exchange<T>(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) Increment(Int32) Increment(Int32) Increment(Int32)

以原子操作的形式递增指定变量的值并存储结果。Increments a specified variable and stores the result, as an atomic operation.

Increment(Int64) Increment(Int64) Increment(Int64) Increment(Int64)

以原子操作的形式递增指定变量的值并存储结果。Increments a specified variable and stores the result, as an atomic operation.

MemoryBarrier() MemoryBarrier() MemoryBarrier() MemoryBarrier()

按如下方式同步内存访问:执行当前线程的处理器在对指令重新排序时,不能先执行 MemoryBarrier() 调用之后的内存存取,再执行 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() MemoryBarrierProcessWide() MemoryBarrierProcessWide() MemoryBarrierProcessWide()

提供覆盖整个过程的内存屏障,确保来自任何 CPU 的读写都不能越过该屏障。Provides a process-wide memory barrier that ensures that reads and writes from any CPU cannot move across the barrier.

Read(Int64) Read(Int64) Read(Int64) Read(Int64)

返回一个以原子操作形式加载的 64 位值。Returns a 64-bit value, loaded as an atomic operation.

SpeculationBarrier() SpeculationBarrier() SpeculationBarrier() SpeculationBarrier()

定义内存防护,用于阻止超过此点的预测执行,直至完成挂起的读取和写入操作。Defines a memory fence that blocks speculative execution past this point until pending reads and writes are complete.

适用于

线程安全性

此类型是线程安全的。This type is thread safe.

另请参阅