Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# Stack.Synchronized() 메서드 완벽 가이드: 스레드 안전 스택 만들기

C#의 Stack.Synchronized() 메서드는 기존 Stack 컬렉션을 감싸는 동기화된(스레드로부터 안전한, thread-safe) 래퍼(wrapper)를 반환합니다. 멀티스레드 환경에서 여러 스레드가 동시에 하나의 스택에 접근할 때 발생할 수 있는 데이터 손상이나 경합 조건(race condition)을 방지하고자 할 때 유용하게 사용됩니다.

구문(Syntax)

Stack.Synchronized() 메서드의 구문은 다음과 같습니다.

public static System.Collections.Stack Synchronized (System.Collections.Stack stack);

매개변수 stack은 동기화할 대상이 되는 스택입니다. 이 메서드는 원본 스택 자체를 수정하지 않고, 동기화가 적용된 새로운 래퍼 객체를 반환한다는 점에 유의해야 합니다.

예제 1: 정수형 스택에서의 사용

다음 예제는 정수 요소를 담은 스택에 Synchronized() 메서드를 적용하는 방법을 보여줍니다.

using System;
using System.Collections;
public class Demo {
    public static void Main() {
        Stack stack = new Stack();
        stack.Push(150);
        stack.Push(300);
        stack.Push(500);
        stack.Push(750);
        stack.Push(1000);
        stack.Push(1250);
        stack.Push(1500);
        stack.Push(2000);
        stack.Push(2500);
        Console.WriteLine("Stack elements...");
        foreach(int val in stack) {
            Console.WriteLine(val);
        }
        Console.WriteLine("Count of elements = "+stack.Count);
        Console.WriteLine("Element 750 is the stack? = "+stack.Contains(750));
        stack.Push(3000);
        Console.WriteLine("\nStack elements...updated");
        foreach(int val in stack) {
            Console.WriteLine(val);
        }
        Console.WriteLine("Count of elements (updated) = "+stack.Count);
        Console.WriteLine("Element 5000 is the stack? = "+stack.Contains(5000));
        Stack stack2 = (Stack)stack.Clone();
        Console.WriteLine("\nStack elements...cloned");
        foreach(int val in stack2) {
            Console.WriteLine(val);
        }
        Console.Write("Count of elements (updated) = "+stack2.Count);
        Console.WriteLine("Is the Stack synchronized? = "+stack.IsSynchronized);
        Stack stack3 = Stack.Synchronized(stack);
        Console.WriteLine("Is the Stack synchronized? = "+stack3.IsSynchronized);
    }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Stack elements...
2500
2000
1500
1250
1000
750
500
300
150
Count of elements = 9
Element 750 is the stack? = True

Stack elements...updated
3000
2500
2000
1500
1250
1000
750
500
300
150
Count of elements (updated) = 10
Element 5000 is the stack? = False

Stack elements...cloned
3000
2500
2000
1500
1250
1000
750
500
300
150
Count of elements (updated) = 10Is the Stack synchronized? = False
Is the Stack synchronized? = True

예제 2: 문자열 스택에서의 사용

이번에는 문자열 요소를 담은 스택으로 동일한 개념을 확인해 보겠습니다.

using System;
using System.Collections;
public class Demo {
    public static void Main() {
        Stack stack = new Stack();
        stack.Push("Inspiron");
        stack.Push("Alienware");
        stack.Push("Projectors");
        stack.Push("Monitors");
        stack.Push("XPS");
        stack.Push("Laptop");
        stack.Push("Notebook");
        Console.WriteLine("Stack elements...");
        foreach(string val in stack) {
            Console.WriteLine(val);
        }
        Console.WriteLine("Count of elements = "+stack.Count);
        stack.Push("Ultrabook");
        stack.Push("Cameras");
        stack.Push("Keyboards");
        Console.WriteLine("\nStack elements...updated");
        foreach(string val in stack) {
            Console.WriteLine(val);
        }
        Console.WriteLine("\nCount of elements (updated) = "+stack.Count);
        Console.WriteLine("Is the Stack synchronized? = "+stack.IsSynchronized);
        Stack stack2 = Stack.Synchronized(stack);
        Console.WriteLine("Is the Stack synchronized? = "+stack2.IsSynchronized);
    }
}

출력 결과

위 코드의 실행 결과는 다음과 같습니다.

Stack elements...
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements = 7
Stack elements...updated
Keyboards
Cameras
Ultrabook
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements (updated) = 10
Is the Stack synchronized? = False
Is the Stack synchronized? = True

핵심 포인트 정리

  • IsSynchronized 속성: 일반 Stack 객체는 False를 반환하지만, Synchronized() 메서드로 생성된 래퍼는 True를 반환합니다.
  • 래퍼 방식: Synchronized()는 원본 스택을 변경하지 않으며, 모든 작업을 내부적으로 잠금(lock) 처리하여 스레드 안전성을 보장하는 래퍼를 반환합니다.
  • LIFO 구조 확인: 출력 결과에서 볼 수 있듯이 스택은 마지막에 Push한 요소가 가장 먼저 출력되는 후입선출(LIFO) 구조를 따릅니다.