Interlocked.CompareExchange 메서드

정의

같음의 두 값을 비교하고 같은 경우 첫 번째 값을 원자성 연산으로 바꿉니다.

오버로드

Name Description
CompareExchange(UIntPtr, UIntPtr, UIntPtr)

네이티브 크기의 부호 없는 두 정수가 같은지 비교하고, 같은 경우 첫 번째 정수는 원자성 연산으로 바꿉니다.

CompareExchange(UInt64, UInt64, UInt64)

두 개의 64비트 부호 없는 정수가 같은지 비교하고, 같은 경우 첫 번째 값을 원자성 연산으로 바꿉니다.

CompareExchange(UInt32, UInt32, UInt32)

두 개의 32비트 부호 없는 정수가 같은지 비교하고, 같은 경우 첫 번째 값을 원자성 연산으로 바꿉니다.

CompareExchange(UInt16, UInt16, UInt16)

두 개의 16비트 부속 정수가 같은지 비교하고, 같으면 첫 번째 값을 원자성 연산으로 바꿉니다.

CompareExchange(Single, Single, Single)

두 개의 단정밀도 부동 소수점 숫자를 같음으로 비교하고, 같은 경우 첫 번째 값을 원자성 연산으로 바꿉니다.

CompareExchange(Object, Object, Object)

두 개체를 참조 같음으로 비교하고 같은 경우 첫 번째 개체를 원자성 연산으로 바꿉니다.

CompareExchange(SByte, SByte, SByte)

두 개의 8비트 부속 정수가 같은지 비교하고, 같으면 첫 번째 값을 원자성 연산으로 바꿉니다.

CompareExchange(Int64, Int64, Int64)

두 개의 64비트 부속 정수가 같은지 비교하고, 같은 경우 첫 번째 값을 원자성 연산으로 바꿉니다.

CompareExchange(Int32, Int32, Int32)

두 개의 32비트 부속 정수가 같은지 비교하고, 같으면 첫 번째 값을 원자성 연산으로 바꿉니다.

CompareExchange(Int16, Int16, Int16)

두 개의 16비트 부호 없는 정수가 같은지 비교하고, 같은 경우 첫 번째 값을 원자성 연산으로 바꿉니다.

CompareExchange(Double, Double, Double)

두 개의 배정밀도 부동 소수점 숫자를 같음으로 비교하고, 같은 경우 첫 번째 값을 원자성 연산으로 바꿉니다.

CompareExchange(Byte, Byte, Byte)

두 개의 8비트 부호 없는 정수가 같은지 비교하고, 같은 경우 첫 번째 값을 원자성 연산으로 바꿉니다.

CompareExchange(IntPtr, IntPtr, IntPtr)

두 개의 네이티브 크기의 부가 정수가 같은지 비교하고, 같은 경우 첫 번째 정수는 원자성 연산으로 바꿉니다.

CompareExchange<T>(T, T, T)

지정된 형식 T 의 두 인스턴스를 참조 같음으로 비교하고, 같은 경우 첫 번째 인스턴스를 원자성 연산으로 바꿉니다.

CompareExchange(UIntPtr, UIntPtr, UIntPtr)

Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs

Important

이 API는 CLS 규격이 아닙니다.

네이티브 크기의 부호 없는 두 정수가 같은지 비교하고, 같은 경우 첫 번째 정수는 원자성 연산으로 바꿉니다.

public:
 static UIntPtr CompareExchange(UIntPtr % location1, UIntPtr value, UIntPtr comparand);
[System.CLSCompliant(false)]
public static UIntPtr CompareExchange(ref UIntPtr location1, UIntPtr value, UIntPtr comparand);
[<System.CLSCompliant(false)>]
static member CompareExchange : unativeint * unativeint * unativeint -> unativeint
Public Shared Function CompareExchange (ByRef location1 As UIntPtr, value As UIntPtr, comparand As UIntPtr) As UIntPtr

매개 변수

location1
UIntPtr

unativeint

해당 값이 값과 comparand 비교되고 대체될 수 있는 value대상입니다.

value
UIntPtr

unativeint

비교 결과가 같은 경우 대상 값을 대체하는 값입니다.

comparand
UIntPtr

unativeint

의 값과 비교되는 값 location1입니다.

반품

UIntPtr

unativeint

의 원래 값입니다 location1.

특성

예외

주소 location1 는 포인터입니다 null .

적용 대상

CompareExchange(UInt64, UInt64, UInt64)

Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs

Important

이 API는 CLS 규격이 아닙니다.

두 개의 64비트 부호 없는 정수가 같은지 비교하고, 같은 경우 첫 번째 값을 원자성 연산으로 바꿉니다.

public:
 static System::UInt64 CompareExchange(System::UInt64 % location1, System::UInt64 value, System::UInt64 comparand);
[System.CLSCompliant(false)]
public static ulong CompareExchange(ref ulong location1, ulong value, ulong comparand);
[<System.CLSCompliant(false)>]
static member CompareExchange : uint64 * uint64 * uint64 -> uint64
Public Shared Function CompareExchange (ByRef location1 As ULong, value As ULong, comparand As ULong) As ULong

매개 변수

location1
UInt64

값이 비교되고 대체될 comparand 수 있는 대상입니다.

value
UInt64

비교 결과가 같은 경우 대상 값을 대체하는 값입니다.

comparand
UInt64

의 값과 비교되는 값 location1입니다.

반품

의 원래 값입니다 location1.

특성

예외

주소 location1 는 포인터입니다 null .

적용 대상

CompareExchange(UInt32, UInt32, UInt32)

Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs

Important

이 API는 CLS 규격이 아닙니다.

두 개의 32비트 부호 없는 정수가 같은지 비교하고, 같은 경우 첫 번째 값을 원자성 연산으로 바꿉니다.

public:
 static System::UInt32 CompareExchange(System::UInt32 % location1, System::UInt32 value, System::UInt32 comparand);
[System.CLSCompliant(false)]
public static uint CompareExchange(ref uint location1, uint value, uint comparand);
[<System.CLSCompliant(false)>]
static member CompareExchange : uint32 * uint32 * uint32 -> uint32
Public Shared Function CompareExchange (ByRef location1 As UInteger, value As UInteger, comparand As UInteger) As UInteger

매개 변수

location1
UInt32

값이 비교되고 대체될 comparand 수 있는 대상입니다.

value
UInt32

비교 결과가 같은 경우 대상 값을 대체하는 값입니다.

comparand
UInt32

의 값과 비교되는 값 location1입니다.

반품

의 원래 값입니다 location1.

특성

예외

주소 location1 는 포인터입니다 null .

적용 대상

CompareExchange(UInt16, UInt16, UInt16)

Source:
Interlocked.cs
Source:
Interlocked.cs

Important

이 API는 CLS 규격이 아닙니다.

두 개의 16비트 부속 정수가 같은지 비교하고, 같으면 첫 번째 값을 원자성 연산으로 바꿉니다.

public:
 static System::UInt16 CompareExchange(System::UInt16 % location1, System::UInt16 value, System::UInt16 comparand);
[System.CLSCompliant(false)]
public static ushort CompareExchange(ref ushort location1, ushort value, ushort comparand);
[<System.CLSCompliant(false)>]
static member CompareExchange : uint16 * uint16 * uint16 -> uint16
Public Shared Function CompareExchange (ByRef location1 As UShort, value As UShort, comparand As UShort) As UShort

매개 변수

location1
UInt16

값이 비교되고 대체될 comparand 수 있는 대상입니다.

value
UInt16

비교 결과가 같은 경우 대상 값을 대체하는 값입니다.

comparand
UInt16

의 값과 비교되는 값 location1입니다.

반품

의 원래 값입니다 location1.

특성

예외

주소 location1 는 포인터입니다 null .

적용 대상

CompareExchange(Single, Single, Single)

Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs

두 개의 단정밀도 부동 소수점 숫자를 같음으로 비교하고, 같은 경우 첫 번째 값을 원자성 연산으로 바꿉니다.

public:
 static float CompareExchange(float % location1, float value, float comparand);
public static float CompareExchange(ref float location1, float value, float comparand);
static member CompareExchange : single * single * single -> single
Public Shared Function CompareExchange (ByRef location1 As Single, value As Single, comparand As Single) As Single

매개 변수

location1
Single

값이 비교되고 대체될 comparand 수 있는 대상입니다.

value
Single

비교 결과가 같은 경우 대상 값을 대체하는 값입니다.

comparand
Single

의 값과 비교되는 값 location1입니다.

반품

의 원래 값입니다 location1.

예외

주소 location1 는 null 포인터입니다.

예제

다음 코드 예제에서는 실행 중인 총 Single 값을 누적하는 스레드로부터 안전한 메서드를 보여 줍니다. 두 스레드는 스레드로부터 안전한 메서드와 일반 추가를 사용하여 일련의 Single 값을 추가하고 스레드가 완료되면 합계를 비교합니다. 이중 프로세서 컴퓨터에서는 합계에 상당한 차이가 있습니다.

스레드로부터 안전한 메서드에서 실행 합계의 초기 값이 저장되고, 이 CompareExchange 메서드는 새로 계산된 합계를 이전 합계와 교환하는 데 사용됩니다. 반환 값이 실행 중인 합계의 저장된 값과 같지 않으면 다른 스레드가 그 동안 합계를 업데이트했습니다. 이 경우 실행 중인 합계를 업데이트하려는 시도가 반복되어야 합니다.

// This example demonstrates a thread-safe method that adds to a
// running total.  
using System;
using 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 float totalValue = 0.0F;

    // The Total property returns the running total.
    public float Total { get { return totalValue; }}

    // AddToTotal safely adds a value to the running total.
    public float AddToTotal(float addend)
    {
        float initialValue, computedValue;
        do
        {
            // 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.
        }
        while (initialValue != Interlocked.CompareExchange(ref 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;
    }
}

public class Test
{
    // Create an instance of the ThreadSafe class to test.
    private static ThreadSafe ts = new ThreadSafe();
    private static float control;

    private static Random r = new Random();
    private static ManualResetEvent mre = new ManualResetEvent(false);

    public static void Main()
    {
        // Create two threads, name them, and start them. The
        // thread will block on mre.
        Thread t1 = new Thread(TestThread);
        t1.Name = "Thread 1";
        t1.Start();
        Thread t2 = new Thread(TestThread);
        t2.Name = "Thread 2";
        t2.Start();

        // Now let the threads begin adding random numbers to 
        // the total.
        mre.Set();
        
        // Wait until all the threads are done.
        t1.Join();
        t2.Join();

        Console.WriteLine("Thread safe: {0}  Ordinary float: {1}", 
            ts.Total, control);
    }

    private static void TestThread()
    {
        // Wait until the signal.
        mre.WaitOne();

        for(int i = 1; i <= 1000000; i++)
        {
            // Add to the running total in the ThreadSafe instance, and
            // to an ordinary float.
            //
            float testValue = (float) r.NextDouble();
            control += testValue;
            ts.AddToTotal(testValue);
        }
    }
}

/* On a dual-processor computer, this code example produces output 
   similar to the following:

Thread safe: 17039.57  Ordinary float: 15706.44
 */
' 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
        Get
            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
        Do
            ' 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"
        t1.Start()
        Dim t2 As New Thread(AddressOf TestThread)
        t2.Name = "Thread 2"
        t2.Start()

        ' Now let the threads begin adding random numbers to 
        ' the total.
        mre.Set()
        
        ' Wait until all the threads are done.
        t1.Join()
        t2.Join()

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

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

        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
            ts.AddToTotal(testValue)
        Next
    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

설명

location1 이 같 value 으면 comparand 에 저장됩니다location1. 그렇지 않으면 작업이 수행되지 않습니다. 비교 및 교환 작업은 원자성 연산으로 수행됩니다. 반환 값 CompareExchange 은 교환이 발생하는지 여부에 관계없이 원래 값 location1입니다.

추가 정보

적용 대상

CompareExchange(Object, Object, Object)

Source:
Interlocked.CoreCLR.cs
Source:
Interlocked.CoreCLR.cs
Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.CoreCLR.cs

두 개체를 참조 같음으로 비교하고 같은 경우 첫 번째 개체를 원자성 연산으로 바꿉니다.

public:
 static System::Object ^ CompareExchange(System::Object ^ % location1, System::Object ^ value, System::Object ^ comparand);
public static object CompareExchange(ref object location1, object value, object comparand);
public static object? CompareExchange(ref object? location1, object? value, object? comparand);
static member CompareExchange : obj * obj * obj -> obj
Public Shared Function CompareExchange (ByRef location1 As Object, value As Object, comparand As Object) As Object

매개 변수

location1
Object

참조 comparand 로 비교되고 대체될 수 있는 대상 개체입니다.

value
Object

참조 비교 결과 같은 경우 대상 개체를 대체 하는 개체입니다.

comparand
Object

에서 개체에 대한 참조로 비교되는 개체 location1입니다.

반품

의 원래 값입니다 location1.

예외

주소 location1 는 포인터입니다 null .

설명

중요하다

CompareExchange<T>(T, T, T) 메서드 오버로드는 구체적인 참조 형식에 사용할 수 있는 제네릭 대안을 제공합니다.

개체가 참조로 같으면 comparand 에 저장됩니다location1.valuelocation1 그렇지 않으면 작업이 수행되지 않습니다. 비교 및 교환 작업은 원자성 연산으로 수행됩니다. 반환 값 CompareExchange 은 교환이 발생하는지 여부에 관계없이 원래 값 location1입니다.

메모

개체는 값 같음이 아닌 참조 같음으로 비교됩니다. 따라서 동일한 값 형식의 두 개의 boxed 인스턴스(예: 정수 3)는 항상 같지 않은 것으로 나타나며 작업이 수행되지 않습니다. 값 형식에는 이 오버로드를 사용하지 마세요.

추가 정보

적용 대상

CompareExchange(SByte, SByte, SByte)

Source:
Interlocked.cs
Source:
Interlocked.cs

Important

이 API는 CLS 규격이 아닙니다.

두 개의 8비트 부속 정수가 같은지 비교하고, 같으면 첫 번째 값을 원자성 연산으로 바꿉니다.

public:
 static System::SByte CompareExchange(System::SByte % location1, System::SByte value, System::SByte comparand);
[System.CLSCompliant(false)]
public static sbyte CompareExchange(ref sbyte location1, sbyte value, sbyte comparand);
[<System.CLSCompliant(false)>]
static member CompareExchange : sbyte * sbyte * sbyte -> sbyte
Public Shared Function CompareExchange (ByRef location1 As SByte, value As SByte, comparand As SByte) As SByte

매개 변수

location1
SByte

값이 비교되고 대체될 comparand 수 있는 대상입니다.

value
SByte

비교 결과가 같은 경우 대상 값을 대체하는 값입니다.

comparand
SByte

의 값과 비교되는 값 location1입니다.

반품

의 원래 값입니다 location1.

특성

예외

주소 location1 는 포인터입니다 null .

적용 대상

CompareExchange(Int64, Int64, Int64)

Source:
Interlocked.CoreCLR.cs
Source:
Interlocked.CoreCLR.cs
Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.CoreCLR.cs

두 개의 64비트 부속 정수가 같은지 비교하고, 같은 경우 첫 번째 값을 원자성 연산으로 바꿉니다.

public:
 static long CompareExchange(long % location1, long value, long comparand);
public static long CompareExchange(ref long location1, long value, long comparand);
static member CompareExchange : int64 * int64 * int64 -> int64
Public Shared Function CompareExchange (ByRef location1 As Long, value As Long, comparand As Long) As Long

매개 변수

location1
Int64

값이 비교되고 대체될 comparand 수 있는 대상입니다.

value
Int64

비교 결과가 같은 경우 대상 값을 대체하는 값입니다.

comparand
Int64

의 값과 비교되는 값 location1입니다.

반품

의 원래 값입니다 location1.

예외

주소 location1 는 null 포인터입니다.

설명

location1 이 같 value 으면 comparand 에 저장됩니다location1. 그렇지 않으면 작업이 수행되지 않습니다. 비교 및 교환 작업은 원자성 연산으로 수행됩니다. 반환 값 CompareExchange 은 교환이 발생하는지 여부에 관계없이 원래 값 location1입니다.

추가 정보

적용 대상

CompareExchange(Int32, Int32, Int32)

Source:
Interlocked.CoreCLR.cs
Source:
Interlocked.CoreCLR.cs
Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.CoreCLR.cs

두 개의 32비트 부속 정수가 같은지 비교하고, 같으면 첫 번째 값을 원자성 연산으로 바꿉니다.

public:
 static int CompareExchange(int % location1, int value, int comparand);
public static int CompareExchange(ref int location1, int value, int comparand);
static member CompareExchange : int * int * int -> int
Public Shared Function CompareExchange (ByRef location1 As Integer, value As Integer, comparand As Integer) As Integer

매개 변수

location1
Int32

값이 비교되고 대체될 comparand 수 있는 대상입니다.

value
Int32

비교 결과가 같은 경우 대상 값을 대체하는 값입니다.

comparand
Int32

의 값과 비교되는 값 location1입니다.

반품

의 원래 값입니다 location1.

예외

주소 location1 는 null 포인터입니다.

예제

다음 코드 예제에서는 실행 중인 합계를 누적하는 스레드로부터 안전한 메서드를 보여 줍니다. 실행 중인 합계의 초기 값이 저장 CompareExchange 되고 새로 계산된 합계를 이전 합계와 교환하는 데 메서드가 사용됩니다. 반환 값이 실행 중인 합계의 저장된 값과 같지 않으면 다른 스레드가 그 동안 합계를 업데이트했습니다. 이 경우 실행 중인 합계를 업데이트하려는 시도가 반복되어야 합니다.

메모

이 메서드는 Add 정수에 대한 스레드로부터 안전한 실행 합계를 누적하는 보다 편리한 방법을 제공합니다.

// This example demonstrates a thread-safe method that adds to a
// running total.  It cannot be run directly.  You can compile it
// as a library, or add the class to a project.
using System.Threading;

public class ThreadSafe {
    // totalValue contains a running total that can be updated
    // by multiple threads. It must be protected from unsynchronized 
    // access.
    private int totalValue = 0;

    // The Total property returns the running total.
    public int Total {
        get { return totalValue; }
    }

    // AddToTotal safely adds a value to the running total.
    public int AddToTotal(int addend) {
        int initialValue, computedValue;
        do {
            // 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.
        } while (initialValue != Interlocked.CompareExchange(
            ref 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;
    }
}
' This example demonstrates a thread-safe method that adds to a
' running total.  It cannot be run directly.  You can compile it
' as a library, or add the class to a project.
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 Integer = 0

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

    ' AddToTotal safely adds a value to the running total.
    Public Function AddToTotal(ByVal addend As Integer) As Integer
        Dim initialValue, computedValue As Integer
        Do
            ' 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

설명

location1 이 같 value 으면 comparand 에 저장됩니다location1. 그렇지 않으면 작업이 수행되지 않습니다. 비교 및 교환 작업은 원자성 연산으로 수행됩니다. 반환 값 CompareExchange 은 교환이 발생하는지 여부에 관계없이 원래 값 location1입니다.

추가 정보

적용 대상

CompareExchange(Int16, Int16, Int16)

Source:
Interlocked.cs
Source:
Interlocked.cs

두 개의 16비트 부호 없는 정수가 같은지 비교하고, 같은 경우 첫 번째 값을 원자성 연산으로 바꿉니다.

public:
 static short CompareExchange(short % location1, short value, short comparand);
public static short CompareExchange(ref short location1, short value, short comparand);
static member CompareExchange : int16 * int16 * int16 -> int16
Public Shared Function CompareExchange (ByRef location1 As Short, value As Short, comparand As Short) As Short

매개 변수

location1
Int16

값이 비교되고 대체될 comparand 수 있는 대상입니다.

value
Int16

비교 결과가 같은 경우 대상 값을 대체하는 값입니다.

comparand
Int16

의 값과 비교되는 값 location1입니다.

반품

의 원래 값입니다 location1.

예외

주소 location1 는 포인터입니다 null .

적용 대상

CompareExchange(Double, Double, Double)

Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs

두 개의 배정밀도 부동 소수점 숫자를 같음으로 비교하고, 같은 경우 첫 번째 값을 원자성 연산으로 바꿉니다.

public:
 static double CompareExchange(double % location1, double value, double comparand);
public static double CompareExchange(ref double location1, double value, double comparand);
static member CompareExchange : double * double * double -> double
Public Shared Function CompareExchange (ByRef location1 As Double, value As Double, comparand As Double) As Double

매개 변수

location1
Double

값이 비교되고 대체될 comparand 수 있는 대상입니다.

value
Double

비교 결과가 같은 경우 대상 값을 대체하는 값입니다.

comparand
Double

의 값과 비교되는 값 location1입니다.

반품

의 원래 값입니다 location1.

예외

주소 location1 는 null 포인터입니다.

예제

다음 코드 예제에서는 실행 중인 총 Double 값을 누적하는 스레드로부터 안전한 메서드를 보여 줍니다. 두 스레드는 스레드로부터 안전한 메서드와 일반 추가를 사용하여 일련의 Double 값을 추가하고 스레드가 완료되면 합계를 비교합니다. 이중 프로세서 컴퓨터에서는 합계에 상당한 차이가 있습니다.

스레드로부터 안전한 메서드에서 실행 합계의 초기 값이 저장되고, 이 CompareExchange 메서드는 새로 계산된 합계를 이전 합계와 교환하는 데 사용됩니다. 반환 값이 실행 중인 합계의 저장된 값과 같지 않으면 다른 스레드가 그 동안 합계를 업데이트했습니다. 이 경우 실행 중인 합계를 업데이트하려는 시도가 반복되어야 합니다.

// This example demonstrates a thread-safe method that adds to a
// running total.  
using System;
using 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 double totalValue = 0.0;

    // The Total property returns the running total.
    public double Total { get { return totalValue; }}

    // AddToTotal safely adds a value to the running total.
    public double AddToTotal(double addend)
    {
        double initialValue, computedValue;
        do
        {
            // 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.
        }
        while (initialValue != Interlocked.CompareExchange(ref 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;
    }
}

public class Test
{
    // Create an instance of the ThreadSafe class to test.
    private static ThreadSafe ts = new ThreadSafe();
    private static double control;

    private static Random r = new Random();
    private static ManualResetEvent mre = new ManualResetEvent(false);

    public static void Main()
    {
        // Create two threads, name them, and start them. The
        // thread will block on mre.
        Thread t1 = new Thread(TestThread);
        t1.Name = "Thread 1";
        t1.Start();
        Thread t2 = new Thread(TestThread);
        t2.Name = "Thread 2";
        t2.Start();

        // Now let the threads begin adding random numbers to 
        // the total.
        mre.Set();
        
        // Wait until all the threads are done.
        t1.Join();
        t2.Join();

        Console.WriteLine("Thread safe: {0}  Ordinary Double: {1}", 
            ts.Total, control);
    }

    private static void TestThread()
    {
        // Wait until the signal.
        mre.WaitOne();

        for(int i = 1; i <= 1000000; i++)
        {
            // Add to the running total in the ThreadSafe instance, and
            // to an ordinary double.
            //
            double testValue = r.NextDouble();
            control += testValue;
            ts.AddToTotal(testValue);
        }
    }
}

/* On a dual-processor computer, this code example produces output 
   similar to the following:

Thread safe: 998068.049623744  Ordinary Double: 759775.417190589
 */
' 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 Double = 0.0

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

    ' AddToTotal safely adds a value to the running total.
    Public Function AddToTotal(ByVal addend As Double) As Double
        Dim initialValue, computedValue As Double
        Do
            ' 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 Double

    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"
        t1.Start()
        Dim t2 As New Thread(AddressOf TestThread)
        t2.Name = "Thread 2"
        t2.Start()

        ' Now let the threads begin adding random numbers to 
        ' the total.
        mre.Set()
        
        ' Wait until all the threads are done.
        t1.Join()
        t2.Join()

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

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

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

' On a dual-processor computer, this code example produces output 
' similar to the following:
'
'Thread safe: 998068.049623744  Ordinary Double: 759775.417190589

설명

location1 이 같 value 으면 comparand 에 저장됩니다location1. 그렇지 않으면 작업이 수행되지 않습니다. 비교 및 교환 작업은 원자성 연산으로 수행됩니다. 반환 값 CompareExchange 은 교환이 발생하는지 여부에 관계없이 원래 값 location1입니다.

추가 정보

적용 대상

CompareExchange(Byte, Byte, Byte)

Source:
Interlocked.cs
Source:
Interlocked.cs

두 개의 8비트 부호 없는 정수가 같은지 비교하고, 같은 경우 첫 번째 값을 원자성 연산으로 바꿉니다.

public:
 static System::Byte CompareExchange(System::Byte % location1, System::Byte value, System::Byte comparand);
public static byte CompareExchange(ref byte location1, byte value, byte comparand);
static member CompareExchange : byte * byte * byte -> byte
Public Shared Function CompareExchange (ByRef location1 As Byte, value As Byte, comparand As Byte) As Byte

매개 변수

location1
Byte

값이 비교되고 대체될 comparand 수 있는 대상입니다.

value
Byte

비교 결과가 같은 경우 대상 값을 대체하는 값입니다.

comparand
Byte

의 값과 비교되는 값 location1입니다.

반품

의 원래 값입니다 location1.

예외

주소 location1 는 포인터입니다 null .

적용 대상

CompareExchange(IntPtr, IntPtr, IntPtr)

Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.cs

두 개의 네이티브 크기의 부가 정수가 같은지 비교하고, 같은 경우 첫 번째 정수는 원자성 연산으로 바꿉니다.

public:
 static IntPtr CompareExchange(IntPtr % location1, IntPtr value, IntPtr comparand);
public static IntPtr CompareExchange(ref IntPtr location1, IntPtr value, IntPtr comparand);
static member CompareExchange : nativeint * nativeint * nativeint -> nativeint
Public Shared Function CompareExchange (ByRef location1 As IntPtr, value As IntPtr, comparand As IntPtr) As IntPtr

매개 변수

location1
IntPtr

nativeint

해당 값이 값과 comparand 비교되고 대체될 수 있는 value대상입니다.

value
IntPtr

nativeint

비교 결과가 같은 경우 대상 값을 대체하는 값입니다.

comparand
IntPtr

nativeint

의 값과 비교되는 값 location1입니다.

반품

IntPtr

nativeint

의 원래 값입니다 location1.

예외

주소 location1 는 null 포인터입니다.

설명

location1 이 같 value 으면 comparand 에 저장됩니다location1. 그렇지 않으면 작업이 수행되지 않습니다. 비교 및 교환 작업은 원자성 연산으로 수행됩니다. 이 메서드의 반환 값은 교환이 수행되는지 여부에 관계없이 원래 값 location1입니다.

메모

IntPtr 는 플랫폼별 형식입니다.

추가 정보

적용 대상

CompareExchange<T>(T, T, T)

Source:
Interlocked.cs
Source:
Interlocked.cs
Source:
Interlocked.CoreCLR.cs
Source:
Interlocked.CoreCLR.cs
Source:
Interlocked.CoreCLR.cs

지정된 형식 T 의 두 인스턴스를 참조 같음으로 비교하고, 같은 경우 첫 번째 인스턴스를 원자성 연산으로 바꿉니다.

public:
generic <typename T>
 where T : class static T CompareExchange(T % location1, T value, T comparand);
public:
generic <typename T>
 static T CompareExchange(T % location1, T value, T comparand);
public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class;
public static T CompareExchange<T>(ref T location1, T value, T comparand);
[System.Runtime.InteropServices.ComVisible(false)]
public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class;
static member CompareExchange : 'T * 'T * 'T -> 'T (requires 'T : null)
static member CompareExchange : 'T * 'T * 'T -> 'T
[<System.Runtime.InteropServices.ComVisible(false)>]
static member CompareExchange : 'T * 'T * 'T -> 'T (requires 'T : null)
Public Shared Function CompareExchange(Of T As Class) (ByRef location1 As T, value As T, comparand As T) As T
Public Shared Function CompareExchange(Of T) (ByRef location1 As T, value As T, comparand As T) As T

형식 매개 변수

T

, valuecomparand에 사용할 location1형식입니다.

매개 변수

location1
T

값이 참조 comparand 로 비교되고 대체될 수 있는 대상입니다. 참조 매개 변수입니다(C#의 경우 ref, Visual Basic ByRef).

value
T

참조를 기준으로 비교하면 대상 값을 대체하는 값입니다.

comparand
T

에 있는 값에 대한 참조로 비교되는 값 location1입니다.

반품

T

의 원래 값입니다 location1.

특성

예외

주소 location1 는 null 포인터입니다.

지원 T 되지 않는 항목이 지정됩니다. .NET 8 이전 버전에서는 T 참조 형식이어야 합니다. .NET 9 이상 버전에서는 T 참조, 기본 형식 또는 열거형 형식이어야 합니다.

설명

값이 참조로 같으면 comparand 에 저장됩니다location1.valuelocation1 그렇지 않으면 작업이 수행되지 않습니다. 비교 및 교환은 원자성 연산으로 수행됩니다. 이 메서드의 반환 값은 교환이 수행되는지 여부에 관계없이 원래 값 location1입니다.

적용 대상