Interlocked.Increment 메서드

정의

원자 단위 연산으로 지정된 변수를 증가시키고 결과를 저장합니다.

오버로드

Increment(UInt64)

원자 단위 연산으로 지정된 변수를 증가시키고 결과를 저장합니다.

Increment(UInt32)

원자 단위 연산으로 지정된 변수를 증가시키고 결과를 저장합니다.

Increment(Int32)

원자 단위 연산으로 지정된 변수를 증가시키고 결과를 저장합니다.

Increment(Int64)

원자 단위 연산으로 지정된 변수를 증가시키고 결과를 저장합니다.

Increment(UInt64)

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

중요

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

원자 단위 연산으로 지정된 변수를 증가시키고 결과를 저장합니다.

public:
 static System::UInt64 Increment(System::UInt64 % location);
[System.CLSCompliant(false)]
public static ulong Increment (ref ulong location);
[<System.CLSCompliant(false)>]
static member Increment : uint64 -> uint64
Public Shared Function Increment (ByRef location As ULong) As ULong

매개 변수

location
UInt64

값을 증가시킬 변수입니다.

반환

증분 작업이 완료된 직후의 변수 값입니다.

특성

예외

location의 주소는 null 포인터입니다.

적용 대상

Increment(UInt32)

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

중요

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

원자 단위 연산으로 지정된 변수를 증가시키고 결과를 저장합니다.

public:
 static System::UInt32 Increment(System::UInt32 % location);
[System.CLSCompliant(false)]
public static uint Increment (ref uint location);
[<System.CLSCompliant(false)>]
static member Increment : uint32 -> uint32
Public Shared Function Increment (ByRef location As UInteger) As UInteger

매개 변수

location
UInt32

값을 증가시킬 변수입니다.

반환

증분 작업이 완료된 직후의 변수 값입니다.

특성

예외

location의 주소는 null 포인터입니다.

적용 대상

Increment(Int32)

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

원자 단위 연산으로 지정된 변수를 증가시키고 결과를 저장합니다.

public:
 static int Increment(int % location);
public static int Increment (ref int location);
static member Increment : int -> int
Public Shared Function Increment (ByRef location As Integer) As Integer

매개 변수

location
Int32

값을 증가시킬 변수입니다.

반환

증분 작업이 완료된 직후의 변수 값입니다.

예외

location의 주소는 null 포인터입니다.

예제

다음 예제에서는 중간점 값이 있는 1,000개의 난수를 생성하기 위해 0에서 1,000까지의 난수 수를 결정합니다. 중간점 값의 수를 추적하기 위해 변수 는 midpointCount0으로 설정되고 난수 생성기가 10,000에 도달할 때까지 중간점 값을 반환할 때마다 증가합니다. 세 개의 스레드가 난수를 Increment(Int32) 생성하기 때문에 메서드가 호출되어 여러 스레드가 동시에 업데이트 midpointCount 되지 않도록 합니다. 잠금은 난수 생성기를 보호하는 데도 사용되며 개체는 메서드가 CountdownEventMain 세 스레드 전에 실행을 완료하지 않도록 하는 데 사용됩니다.

using System;
using System.Threading;

public class Example
{
   const int LOWERBOUND = 0;
   const int UPPERBOUND = 1001;
   
   static Object lockObj = new Object();
   static Random rnd = new Random();
   static CountdownEvent cte;
   
   static int totalCount = 0;
   static int totalMidpoint = 0;
   static int midpointCount = 0;

   public static void Main()
   {
      cte = new CountdownEvent(1);
      // Start three threads. 
      for (int ctr = 0; ctr <= 2; ctr++) {
         cte.AddCount();
         Thread th = new Thread(GenerateNumbers);
         th.Name = "Thread" + ctr.ToString();
         th.Start();
      }
      cte.Signal();
      cte.Wait();
      Console.WriteLine();
      Console.WriteLine("Total midpoint values:  {0,10:N0} ({1:P3})",
                        totalMidpoint, totalMidpoint/((double)totalCount));
      Console.WriteLine("Total number of values: {0,10:N0}", 
                        totalCount);                  
   }

   private static void GenerateNumbers()
   {
      int midpoint = (UPPERBOUND - LOWERBOUND) / 2;
      int value = 0;
      int total = 0;
      int midpt = 0;
      
      do {
         lock (lockObj) {
            value = rnd.Next(LOWERBOUND, UPPERBOUND);
         }
         if (value == midpoint) { 
            Interlocked.Increment(ref midpointCount);
            midpt++;
         }
         total++;    
      } while (Volatile.Read(ref midpointCount) < 10000);
      
      Interlocked.Add(ref totalCount, total);
      Interlocked.Add(ref totalMidpoint, midpt);
      
      string s = String.Format("Thread {0}:\n", Thread.CurrentThread.Name) +
                 String.Format("   Random Numbers: {0:N0}\n", total) + 
                 String.Format("   Midpoint values: {0:N0} ({1:P3})", midpt, 
                               ((double) midpt)/total);
      Console.WriteLine(s);
      cte.Signal();
   }
}
// The example displays output like the following:
//       Thread Thread2:
//          Random Numbers: 2,776,674
//          Midpoint values: 2,773 (0.100 %)
//       Thread Thread1:
//          Random Numbers: 4,876,100
//          Midpoint values: 4,873 (0.100 %)
//       Thread Thread0:
//          Random Numbers: 2,312,310
//          Midpoint values: 2,354 (0.102 %)
//       
//       Total midpoint values:      10,000 (0.100 %)
//       Total number of values:  9,965,084
Imports System.Threading

Module Example
   Const LOWERBOUND As Integer = 0
   Const UPPERBOUND As Integer = 1001
   
   Dim lockObj As New Object()
   Dim rnd As New Random()
   Dim cte As CountdownEvent
   
   Dim totalCount As Integer = 0
   Dim totalMidpoint As Integer = 0
   Dim midpointCount As Integer = 0

   Public Sub Main()
      cte = New CountdownEvent(1)
      ' Start three threads. 
      For ctr As Integer = 0 To 2
         cte.AddCount()
         Dim th As New Thread(AddressOf GenerateNumbers)
         th.Name = "Thread" + ctr.ToString()
         th.Start()
      Next
      cte.Signal()
      cte.Wait()
      Console.WriteLine()
      Console.WriteLine("Total midpoint values:  {0,10:N0} ({1:P3})",
                        totalMidpoint, totalMidpoint/totalCount)
      Console.WriteLine("Total number of values: {0,10:N0}", 
                        totalCount)                  
   End Sub
   
   Private Sub GenerateNumbers()
      Dim midpoint As Integer = (upperBound - lowerBound) \ 2
      Dim value As Integer = 0
      Dim total As Integer = 0
      Dim midpt As Integer = 0
      Do
         SyncLock lockObj
            value = rnd.Next(lowerBound, upperBound)
         End SyncLock
         If value = midpoint Then 
            Interlocked.Increment(midpointCount)
            midpt += 1
         End If
         total += 1    
      Loop While midpointCount < 10000
      
      Interlocked.Add(totalCount, total)
      Interlocked.Add(totalMidpoint, midpt)
      
      Dim s As String = String.Format("Thread {0}:", Thread.CurrentThread.Name) + vbCrLf +
                        String.Format("   Random Numbers: {0:N0}", total) + vbCrLf +
                        String.Format("   Midpoint values: {0:N0} ({1:P3})", midpt, midpt/total)
      Console.WriteLine(s)
      cte.Signal()
   End Sub
End Module
' The example displays output like the following:
'       Thread Thread2:
'          Random Numbers: 2,776,674
'          Midpoint values: 2,773 (0.100 %)
'       Thread Thread1:
'          Random Numbers: 4,876,100
'          Midpoint values: 4,873 (0.100 %)
'       Thread Thread0:
'          Random Numbers: 2,312,310
'          Midpoint values: 2,354 (0.102 %)
'       
'       Total midpoint values:      10,000 (0.100 %)
'       Total number of values:  9,965,084

다음 예제는 스레드 프로시저 대신 클래스를 사용하여 Task 50,000개의 임의 중간점 정수를 생성한다는 점을 제외하고 이전 예제와 비슷합니다. 이 예제에서 람다 식은 스레드 프로시저를 GenerateNumbers 대체하고 메서드를 호출하면 Task.WaitAll 개체가 필요하지 CountdownEvent 않습니다.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   const int LOWERBOUND = 0;
   const int UPPERBOUND = 1001;
   
   static Object lockObj = new Object();
   static Random rnd = new Random();
   
   static int totalCount = 0;
   static int totalMidpoint = 0;
   static int midpointCount = 0;

   public static void Main()
   {
      List<Task> tasks = new List<Task>();
      // Start three tasks. 
      for (int ctr = 0; ctr <= 2; ctr++) 
         tasks.Add(Task.Run( () => { int midpoint = (UPPERBOUND - LOWERBOUND) / 2;
                                     int value = 0;
                                     int total = 0;
                                     int midpt = 0;
                                    
                                     do {
                                        lock (lockObj) {
                                           value = rnd.Next(LOWERBOUND, UPPERBOUND);
                                        }
                                        if (value == midpoint) { 
                                           Interlocked.Increment(ref midpointCount);
                                           midpt++;
                                        }
                                        total++;    
                                     } while (Volatile.Read(ref midpointCount) < 50000);
                                    
                                     Interlocked.Add(ref totalCount, total);
                                     Interlocked.Add(ref totalMidpoint, midpt);
                                    
                                     string s = String.Format("Task {0}:\n", Task.CurrentId) +
                                                String.Format("   Random Numbers: {0:N0}\n", total) + 
                                                String.Format("   Midpoint values: {0:N0} ({1:P3})", midpt, 
                                                              ((double) midpt)/total);
                                     Console.WriteLine(s); } ));
      
      Task.WaitAll(tasks.ToArray());
      Console.WriteLine();
      Console.WriteLine("Total midpoint values:  {0,10:N0} ({1:P3})",
                        totalMidpoint, totalMidpoint/((double)totalCount));
      Console.WriteLine("Total number of values: {0,10:N0}", 
                        totalCount);                  
   }
}
// The example displays output like the following:
//       Task 3:
//          Random Numbers: 10,855,250
//          Midpoint values: 10,823 (0.100 %)
//       Task 1:
//          Random Numbers: 15,243,703
//          Midpoint values: 15,110 (0.099 %)
//       Task 2:
//          Random Numbers: 24,107,425
//          Midpoint values: 24,067 (0.100 %)
//       
//       Total midpoint values:      50,000 (0.100 %)
//       Total number of values: 50,206,378
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Const LOWERBOUND As Integer = 0
   Const UPPERBOUND As Integer = 1001
   
   Dim lockObj As New Object()
   Dim rnd As New Random()
   
   Dim totalCount As Integer = 0
   Dim totalMidpoint As Integer = 0
   Dim midpointCount As Integer = 0

   Public Sub Main()
      Dim tasks As New List(Of Task)()
      ' Start three tasks. 
      For ctr As Integer = 0 To 2
         tasks.Add(Task.Run( Sub()
                                Dim midpoint As Integer = (upperBound - lowerBound) \ 2
                                Dim value As Integer = 0
                                Dim total As Integer = 0
                                Dim midpt As Integer = 0
                                Do
                                   SyncLock lockObj
                                      value = rnd.Next(lowerBound, upperBound)
                                   End SyncLock
                                   If value = midpoint Then 
                                      Interlocked.Increment(midpointCount)
                                      midpt += 1
                                   End If
                                   total += 1    
                                Loop While midpointCount < 50000
                              
                                Interlocked.Add(totalCount, total)
                                Interlocked.Add(totalMidpoint, midpt)
                              
                                Dim s As String = String.Format("Task {0}:", Task.CurrentId) + vbCrLf +
                                                  String.Format("   Random Numbers: {0:N0}", total) + vbCrLf +
                                                  String.Format("   Midpoint values: {0:N0} ({1:P3})", midpt, midpt/total)
                                Console.WriteLine(s)
                             End Sub ))
      Next

      Task.WaitAll(tasks.ToArray())
      Console.WriteLine()
      Console.WriteLine("Total midpoint values:  {0,10:N0} ({1:P3})",
                        totalMidpoint, totalMidpoint/totalCount)
      Console.WriteLine("Total number of values: {0,10:N0}", 
                        totalCount)                  
   End Sub
End Module
' The example displays output like the following:
'       Task 3:
'          Random Numbers: 10,855,250
'          Midpoint values: 10,823 (0.100 %)
'       Task 1:
'          Random Numbers: 15,243,703
'          Midpoint values: 15,110 (0.099 %)
'       Task 2:
'          Random Numbers: 24,107,425
'          Midpoint values: 24,067 (0.100 %)
'       
'       Total midpoint values:      50,000 (0.100 %)
'       Total number of values: 50,206,378

설명

이 메서드는 래핑하여 오버플로 조건을 처리합니다( if location = Int32.MaxValue, location + 1 = Int32.MinValue). 예외는 throw되지 않습니다.

추가 정보

적용 대상

Increment(Int64)

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

원자 단위 연산으로 지정된 변수를 증가시키고 결과를 저장합니다.

public:
 static long Increment(long % location);
public static long Increment (ref long location);
static member Increment : int64 -> int64
Public Shared Function Increment (ByRef location As Long) As Long

매개 변수

location
Int64

값을 증가시킬 변수입니다.

반환

증분 작업이 완료된 직후의 변수 값입니다.

예외

location의 주소는 null 포인터입니다.

설명

이 메서드는 래핑하여 오버플로 조건을 처리합니다( if location = Int64.MaxValue, location + 1 = Int64.MinValue). 예외는 throw되지 않습니다.

추가 정보

적용 대상