반응형
코드 분석 및 설명
위 코드는 C#에서 스레드의 우선순위를 설정하고, CPU 코어를 사용하는 방식에 따라 스레드의 실행 속도가 어떻게 영향을 받는지 보여줍니다. 주요 부분을 단계별로 분석하면 다음과 같습니다.
using System;
using System.Diagnostics;
using System.Threading;
namespace ThreadPriorityDemo
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting thread priority demonstration...");
Console.WriteLine("Current thread priority: {0}", Thread.CurrentThread.Priority);
Console.WriteLine("\n[Running on all available cores]");
RunThreads();
Thread.Sleep(2000);
Console.WriteLine("\n[Running on a single core]");
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1);
RunThreads();
}
static void RunThreads()
{
var sample = new ThreadSample();
var threadOne = new Thread(sample.CountNumbers) { Name = "ThreadOne", Priority = ThreadPriority.Highest };
var threadTwo = new Thread(sample.CountNumbers) { Name = "ThreadTwo", Priority = ThreadPriority.Lowest };
threadOne.Start();
threadTwo.Start();
Thread.Sleep(TimeSpan.FromSeconds(2));
sample.Stop();
threadOne.Join();
threadTwo.Join();
}
class ThreadSample
{
private bool _isStopped;
public void Stop() => _isStopped = true;
public void CountNumbers()
{
long counter = 0;
while (!_isStopped)
{
counter++;
}
Console.WriteLine($"{Thread.CurrentThread.Name} with priority {Thread.CurrentThread.Priority,11} " +
$"counted to {counter:N0}");
}
}
}
}
C# 스레드 우선순위와 CPU 시간 할당 요약
1. 스레드 우선순위 (Thread Priority)
C#에서 스레드 우선순위는 스케줄러가 CPU 시간을 어떻게 분배할지 결정하는 데 도움을 주는 힌트를 제공합니다. 우선순위 옵션은 다음과 같습니다:
- ThreadPriority.Highest: 가장 높은 우선순위.
- ThreadPriority.AboveNormal: 일반보다 높은 우선순위.
- ThreadPriority.Normal: 기본값.
- ThreadPriority.BelowNormal: 일반보다 낮은 우선순위.
- ThreadPriority.Lowest: 가장 낮은 우선순위.
2. 우선순위의 영향
- 우선순위가 높은 스레드는 CPU가 바쁜 상황에서도 더 많은 시간을 할당받습니다.
- 운영 체제는 우선순위 외에도 다른 요인(예: I/O 대기, 시스템 상태)을 고려하여 CPU 시간을 분배합니다.
3. CPU 코어 제어
- Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1);
특정 CPU 코어에 실행 프로세스를 제한합니다. 멀티코어 환경과 단일 코어 환경에서 스레드 동작을 비교할 수 있습니다.
4. 코드 주요 흐름
- 현재 스레드 우선순위 확인실행 중인 메인 스레드의 우선순위를 출력합니다.
- Console.WriteLine("Current thread priority: {0}", Thread.CurrentThread.Priority);
- 스레드 생성 및 실행두 개의 스레드를 생성하고 각기 다른 우선순위를 설정합니다.
- var threadOne = new Thread(sample.CountNumbers) { Name = "ThreadOne", Priority = ThreadPriority.Highest }; var threadTwo = new Thread(sample.CountNumbers) { Name = "ThreadTwo", Priority = ThreadPriority.Lowest };
- 스레드 종료 제어_isStopped를 true로 설정하여 스레드 루프를 중단하고 종료를 기다립니다.
- sample.Stop(); threadOne.Join(); threadTwo.Join();
- 카운트 결과 출력
각 스레드가 수행한 작업 결과(카운터 값)를 출력하며, 우선순위가 높은 스레드가 더 빠르게 카운트를 증가시키는 것을 확인합니다.
5. 실험 결과
- 우선순위가 높은 스레드는 낮은 우선순위 스레드보다 CPU 시간을 더 많이 할당받습니다.
- 단일 코어에서 실행할 경우, 스레드 간의 우선순위 차이가 더 명확하게 나타납니다.
6. 학습 포인트
- C#에서 Thread.Priority는 CPU 스케줄링의 기본 개념을 이해하는 데 유용합니다.
- ProcessorAffinity를 사용하면 CPU 코어 활용 방식을 제어하여 멀티스레드의 성능 차이를 실험할 수 있습니다.
- 스레드 종료 시 Join을 사용하여 안전하게 종료를 관리하는 것이 중요합니다.
반응형
'C# > 쓰레드' 카테고리의 다른 글
C# `Thread`와 `ThreadPool`의 차이점 및 델리게이트 비동기 호출 이해 (17) | 2025.01.16 |
---|---|
C# 스레드풀(Thread Pool): 개념, 사용법, 및 예제 코드 설명 (1) | 2025.01.16 |
C# SemaphoreSlim: 멀티스레드 리소스 접근 제어 예제와 설명 (2) | 2025.01.16 |
C# 스레드 제어: Semaphore와 SemaphoreSlim의 차이와 사용법 (2) | 2025.01.16 |
C# Mutex로 프로세스 단일 인스턴스 제어하기 (2) | 2025.01.16 |
원자적 작업(Atomic Operation): 동시성 문제 해결의 핵심 개념 (2) | 2025.01.16 |
스레드_스레드 상태 조사_thread state (4) | 2025.01.06 |
c# 스레드 기초 (2) | 2025.01.06 |