Interlocked.CompareExchange Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Сравнивает два значения на равенство и, если они равны, заменяет первое.
Перегрузки
CompareExchange(UIntPtr, UIntPtr, UIntPtr) |
Сравнивает два зависящих от платформы обработчика или указателя на равенство и заменяет первое из значений, если они равны. |
CompareExchange(UInt64, UInt64, UInt64) |
Сравнивает два 64-разрядных целых числа без знака и в случае равенства заменяет первое значение. |
CompareExchange(UInt32, UInt32, UInt32) |
Сравнивает два 32-разрядных целых числа без знака и в случае равенства заменяет первое значение. |
CompareExchange(UInt16, UInt16, UInt16) | |
CompareExchange(Single, Single, Single) |
Сравнивает два числа с плавающей запятой с обычной точностью на равенство и, если они равны, заменяет первое значение. |
CompareExchange(Object, Object, Object) |
Сравнивает два объекта на равенство ссылок и заменяет первый объект, если они равны. |
CompareExchange(SByte, SByte, SByte) | |
CompareExchange(Int64, Int64, Int64) |
Сравнивает два 64-разрядных целых числа со знаком на равенство и заменяет первое, если они равны. |
CompareExchange(Int32, Int32, Int32) |
Сравнивает два 32-разрядных целых числа со знаком на равенство и заменяет первое, если они равны. |
CompareExchange(Int16, Int16, Int16) | |
CompareExchange(Double, Double, Double) |
Сравнивает два числа с плавающей запятой двойной точности на равенство и заменяет первое значение, если они равны. |
CompareExchange(Byte, Byte, Byte) | |
CompareExchange(IntPtr, IntPtr, IntPtr) |
Сравнивает два зависящих от платформы обработчика или указателя на равенство и заменяет первое из значений, если они равны. |
CompareExchange<T>(T, T, T) |
Сравнивает два экземпляра указанного ссылочного типа |
CompareExchange(UIntPtr, UIntPtr, UIntPtr)
- Исходный код:
- Interlocked.cs
- Исходный код:
- Interlocked.cs
- Исходный код:
- Interlocked.cs
Важно!
Этот 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
Целевое значение UIntPtr, которое будет сравниваться со значением параметра comparand
и, возможно, будет заменено value
.
- value
-
UIntPtr
unativeint
Значение UIntPtr, которое заменит целевое значение, если результатом сравнения будет равенство.
Возвращаемое значение
unativeint
Исходное значение в позиции location1
.
- Атрибуты
Исключения
Адрес location1
является указателем null
.
Применяется к
CompareExchange(UInt64, UInt64, UInt64)
- Исходный код:
- Interlocked.cs
- Исходный код:
- Interlocked.cs
- Исходный код:
- Interlocked.cs
Важно!
Этот 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)
- Исходный код:
- Interlocked.cs
- Исходный код:
- Interlocked.cs
- Исходный код:
- Interlocked.cs
Важно!
Этот 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)
Важно!
Этот API несовместим с CLS.
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
- value
- UInt16
- comparand
- UInt16
Возвращаемое значение
- Атрибуты
Применяется к
CompareExchange(Single, Single, Single)
- Исходный код:
- Interlocked.cs
- Исходный код:
- Interlocked.cs
- Исходный код:
- 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
является пустым указателем.
Примеры
В следующем примере кода демонстрируется потокобезопасный метод, который накапливает выполняющееся общее количество значений 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
Комментарии
Если comparand
и значение в location1
равны, то value
сохраняется в location1
. В противном случае операция не выполняется. Операции сравнения и обмена выполняются как атомарные операции. Возвращаемое значение CompareExchange — это исходное значение в location1
, независимо от того, выполняется ли обмен.
См. также раздел
Применяется к
CompareExchange(Object, Object, Object)
- Исходный код:
- Interlocked.cs
- Исходный код:
- Interlocked.cs
- Исходный код:
- 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
.
Комментарии
Важно!
Начиная с .NET Framework 2.0 перегрузка метода CompareExchange<T>(T, T, T) предоставляет типобезопасную альтернативу для ссылочных типов. Рекомендуется вызывать его вместо этой перегрузки.
Если comparand
и объект в location1
равны по ссылке, то value
сохраняется в location1
. В противном случае операция не выполняется. Операции сравнения и обмена выполняются как атомарные операции. Возвращаемое значение CompareExchange — это исходное значение в location1
, независимо от того, выполняется ли обмен.
Примечание
Объекты сравниваются на равенство ссылок, а не на равенство значений. В результате два упакованных экземпляра одного и того же типа значения (например, целое число 3) всегда кажутся неравными, и никакие операции не выполняются. Не используйте эту перегрузку с типами значений.
См. также раздел
Применяется к
CompareExchange(SByte, SByte, SByte)
Важно!
Этот API несовместим с CLS.
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
- value
- SByte
- comparand
- SByte
Возвращаемое значение
- Атрибуты
Применяется к
CompareExchange(Int64, Int64, Int64)
- Исходный код:
- Interlocked.cs
- Исходный код:
- Interlocked.cs
- Исходный код:
- 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
является пустым указателем.
Комментарии
Если comparand
и значение в location1
равны, то value
сохраняется в location1
. В противном случае операция не выполняется. Операции сравнения и обмена выполняются как атомарные операции. Возвращаемое значение CompareExchange — это исходное значение в location1
, независимо от того, выполняется ли обмен.
См. также раздел
Применяется к
CompareExchange(Int32, Int32, Int32)
- Исходный код:
- Interlocked.cs
- Исходный код:
- Interlocked.cs
- Исходный код:
- 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
является пустым указателем.
Примеры
В следующем примере кода демонстрируется потокобезопасный метод, который накапливает итог выполнения. Сохраняется начальное значение выполняющегося итога, а затем CompareExchange используется метод для обмена вновь вычисленного итога на старый. Если возвращаемое значение не равно сохраненное значение выполняющегося итогового значения, то в то же время другой поток обновил итоговую сумму. В этом случае необходимо повторить попытку обновить выполняющийся итог.
Примечание
Метод, представленный Add в версии 2.0 платформа .NET Framework, предоставляет более удобный способ накапливать потокобезопасные итоги выполнения для целых чисел.
// 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.dll>
using namespace System::Threading;
public ref class ThreadSafe
{
private:
// totalValue contains a running total that can be updated
// by multiple threads. It must be protected from unsynchronized
// access.
int totalValue;
public:
property int Total
{
// The Total property returns the running total.
int get()
{
return totalValue;
}
}
// AddToTotal safely adds a value to the running total.
int AddToTotal( int addend )
{
int initialValue;
int 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( 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.
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
Комментарии
Если comparand
и значение в location1
равны, то value
сохраняется в location1
. В противном случае операция не выполняется. Операции сравнения и обмена выполняются как атомарные операции. Возвращаемое значение CompareExchange — это исходное значение в location1
, независимо от того, выполняется ли обмен.
См. также раздел
Применяется к
CompareExchange(Int16, Int16, Int16)
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
- value
- Int16
- comparand
- Int16
Возвращаемое значение
Применяется к
CompareExchange(Double, Double, Double)
- Исходный код:
- Interlocked.cs
- Исходный код:
- Interlocked.cs
- Исходный код:
- 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
является пустым указателем.
Примеры
В следующем примере кода демонстрируется потокобезопасный метод, который накапливает выполняющееся общее количество значений 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
Комментарии
Если comparand
и значение в location1
равны, то value
сохраняется в location1
. В противном случае операция не выполняется. Операции сравнения и обмена выполняются как атомарные операции. Возвращаемое значение CompareExchange — это исходное значение в location1
, независимо от того, выполняется ли обмен.
См. также раздел
Применяется к
CompareExchange(Byte, Byte, Byte)
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
- value
- Byte
- comparand
- Byte
Возвращаемое значение
Применяется к
CompareExchange(IntPtr, IntPtr, IntPtr)
- Исходный код:
- Interlocked.cs
- Исходный код:
- Interlocked.cs
- Исходный код:
- 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
Целевое значение IntPtr, которое будет сравниваться со значением параметра comparand
и, возможно, будет заменено value
.
- value
-
IntPtr
nativeint
Значение IntPtr, которое заменит целевое значение, если результатом сравнения будет равенство.
Возвращаемое значение
nativeint
Исходное значение в позиции location1
.
Исключения
Адрес location1
является пустым указателем.
Комментарии
Если comparand
и значение в location1
равны, то value
сохраняется в location1
. В противном случае операция не выполняется. Операции сравнения и обмена выполняются как атомарные операции. Возвращаемое значение этого метода является исходным значением в location1
, независимо от того, выполняется ли обмен.
Примечание
IntPtr — это тип, зависящий от платформы.
См. также раздел
Применяется к
CompareExchange<T>(T, T, T)
- Исходный код:
- Interlocked.CoreCLR.cs
- Исходный код:
- Interlocked.CoreCLR.cs
- Исходный код:
- Interlocked.CoreCLR.cs
Сравнивает два экземпляра указанного ссылочного типа T
на равенство ссылок. Если они равны, заменяет первый экземпляр.
public:
generic <typename T>
where T : class static T CompareExchange(T % location1, T value, T comparand);
public static T CompareExchange<T> (ref T location1, T value, T comparand) where T : class;
[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)
[<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
Параметры типа
- T
Тип, используемый для location1
, value
, и comparand
. Этот тип должен быть ссылочным типом.
Параметры
- location1
- T
Целевой объект, значение которого сравнивается по ссылке с объектом comparand
и, возможно, будет заменено. Это ссылочный параметр (ref
в C#, ByRef
в Visual Basic).
- value
- T
Значение, которым будет заменено целевое значение, если результатом сравнения по ссылке будет равенство.
- comparand
- T
Значение, которое сравнивается по ссылке со значением в позиции location1
.
Возвращаемое значение
Исходное значение в позиции location1
.
- Атрибуты
Исключения
Адрес location1
является пустым указателем.
Комментарии
Если comparand
и значение в location1
равны по ссылке, то value
сохраняется в location1
. В противном случае операция не выполняется. Сравнение и обмен выполняются как атомарная операция. Возвращаемое значение этого метода является исходным значением в location1
, независимо от того, выполняется ли обмен.
Этот метод поддерживает только ссылочные типы. Существуют перегрузки CompareExchange метода для типов Int32значений , Int64, IntPtr, Singleи Double, но другие типы значений не поддерживаются.
Примечание
Эта перегрузка метода предпочтительнее перегрузки CompareExchange(Object, Object, Object) метода, так как для последней требуется доступ к целевому объекту с поздней привязкой.
Применяется к
Обратная связь
https://aka.ms/ContentUserFeedback.
Ожидается в ближайшее время: в течение 2024 года мы постепенно откажемся от GitHub Issues как механизма обратной связи для контента и заменим его новой системой обратной связи. Дополнительные сведения см. в разделеОтправить и просмотреть отзыв по