Interlocked 类

为多个线程共享的变量提供原子操作。

**命名空间:**System.Threading
**程序集:**mscorlib(在 mscorlib.dll 中)

语法

声明
Public NotInheritable Class Interlocked
用法
可对静态类的成员直接进行访问,无需类的实例。
public static class Interlocked
public ref class Interlocked abstract sealed
public final class Interlocked
public final class Interlocked

备注

此类的方法可以防止可能在下列情况发生的错误:计划程序在某个线程正在更新可由其他线程访问的变量时切换上下文;或者当两个线程在不同的处理器上并发执行时。此类的成员不引发异常。

IncrementDecrement 方法递增或递减变量并将结果值存储在单个操作中。在大多数计算机上,增加变量操作不是一个原子操作,需要执行下列步骤:

  1. 将实例变量中的值加载到寄存器中。

  2. 增加或减少该值。

  3. 在实例变量中存储该值。

如果不使用 IncrementDecrement,线程会在执行完前两个步骤后被抢先。然后由另一个线程执行所有三个步骤。当第一个线程重新开始执行时,它改写实例变量中的值,造成第二个线程执行增减操作的结果丢失。

Exchange 方法自动交换指定变量的值。CompareExchange 方法组合了两个操作:比较两个值以及根据比较的结果将第三个值存储在其中一个变量中。比较和交换操作按原子操作执行。

示例

下面的代码示例说明线程安全资源锁定机制。

Imports System
Imports System.Threading

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

        Private Shared currentMso As [Object]
        Private Shared globalMso As New [Object]()
        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 'MyThreadProc

        '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 'UseResource
    End Class 'MyInterlockedExchangeExampleClass 
End Namespace 'InterlockedExchange_Example
using System;
using System.Threading;

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

        private static Object currentMso;
        private static Object globalMso = new Object();
        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;
            }
        }

    }
}  
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;
   static Object^ globalMso = gcnew Object;
};

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();

   }
}
package InterlockedExchange_Example ; 

import System .* ;
import System.Threading .* ;
import System.Threading.Thread;

class MyInterlockedExchangeExampleClass
{
    //0 for false, 1 for true.
    private static int usingResource = 0;
    private static Object currentMso;
    private static Object globalMso = new Object();
    private static int numThreadIterations = 5;
    private static int numThreads = 10;

    public static void main(String[] args)
    {
        Thread myThread;
        Random rnd = new Random();

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

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

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

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

    //A simple method that denies reentrancy.
    static boolean UseResource()
    {
        //0 indicates that the method is not in use.
        if (0 == Interlocked.Exchange(usingResource, 1)) {
            Console.WriteLine("{0} acquired the lock",
                Thread.get_CurrentThread().get_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.get_CurrentThread().get_Name());

            //Release the lock
            Interlocked.Exchange(usingResource, 0);
            return true;
        }
        else {
            Console.WriteLine("   {0} was denied the lock", 
                Thread.get_CurrentThread().get_Name());
            return false;
        }
    } //UseResource
} //MyInterlockedExchangeExampleClass

继承层次结构

System.Object
  System.Threading.Interlocked

线程安全

此类型是线程安全的。

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

Interlocked 成员
System.Threading 命名空间

其他资源

托管线程处理
互锁操作