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

C# Stack.IsSynchronized 속성 완벽 정리 – 스레드 안전 여부 확인 방법

C#에서 Stack.IsSynchronized 속성은 해당 Stack에 대한 접근이 동기화되어 있는지, 즉 스레드로부터 안전(thread-safe)한지 여부를 나타내는 값을 반환합니다.

일반적인 Stack 인스턴스는 기본적으로 동기화되지 않은 상태이므로 이 속성은 False를 반환하며, 멀티스레드 환경에서 안전하게 사용하려면 별도의 동기화 처리가 필요합니다.

구문(Syntax)

public virtual bool IsSynchronized { get; }

예제 1 – 문자열 요소를 가진 Stack

다음 예제는 문자열 요소들을 담은 Stack을 생성하고, IsSynchronized 속성값을 확인하는 과정을 보여줍니다.

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);
        Console.WriteLine("Element Speakers is the stack? = "+stack.Contains("Speakers"));
        stack.Push("Headphone");
        stack.Push("Keyboard");
        stack.Push("Earphone");
        Console.WriteLine("\nStack elements...updated");
        foreach(string val in stack) {
            Console.WriteLine(val);
        }
        Console.WriteLine("Count of elements (updated) = "+stack.Count);
        Console.WriteLine("\nElement Alienware is the stack? = "+stack.Contains("Alienware"));
        Console.WriteLine("Is the Stack synchronized? = "+stack.IsSynchronized);
        Stack stack2 = (Stack)stack.Clone();
        Console.WriteLine("\nStack elements...cloned");
        IEnumerator demoEnum = stack2.GetEnumerator();
        while (demoEnum.MoveNext()) {
            Console.WriteLine(demoEnum.Current);
        }
        Console.WriteLine("Count of elements (updated) = "+stack.Count);
    }
}

실행 결과

Stack elements...
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements = 7
Element Speakers is the stack? = False
Stack elements...updated
Earphone
Keyboard
Headphone
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements (updated) = 10
Element Alienware is the stack? = True
Is the Stack synchronized? = False
Stack elements...cloned
Earphone
Keyboard
Headphone
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements (updated) = 10

위 결과에서 확인할 수 있듯이, 일반적인 방식으로 생성된 Stack의 IsSynchronized 값은 False입니다. 즉, 기본 Stack 객체는 스레드 안전하지 않습니다.

예제 2 – 정수 요소와 Synchronized() 메서드 활용

두 번째 예제는 정수형 요소를 다루며, Stack.Synchronized() 정적 메서드를 통해 동기화된 래퍼(wrapper)를 생성하는 방법을 보여줍니다.

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

핵심 포인트 정리

  • IsSynchronized 속성: Stack이 스레드로부터 안전하게 보호되고 있는지 여부를 bool 값으로 반환합니다.
  • 기본값은 False: 일반적으로 생성된 Stack은 동기화되지 않으므로 단일 스레드 환경에 적합합니다.
  • Stack.Synchronized() 메서드: 기존 Stack을 감싸는 동기화된 래퍼를 반환하여, 멀티스레드 환경에서도 안전하게 사용할 수 있습니다.
  • Clone() 메서드: 얕은 복사(shallow copy)를 수행하며, 복제된 Stack 역시 원본과 마찬가지로 동기화되지 않은 상태입니다.

멀티스레드 프로그래밍에서 컬렉션을 공유해야 하는 경우에는 반드시 Stack.Synchronized()를 사용하거나 직접 lock 구문으로 동기화를 구현하는 것이 좋습니다.