728x90
스레드 우선순위
스레드 우선순위에 대한 다른 가능한 옵션을 설명하며,또한 스레드에 CPU 시간을 어떻게 할당할지 결정하는 스레드 우선 순위를 설정하는 방법을 제시한다.
class Program
{
static void Main(string[] args)
{
// 다른 두 스레드를 정의한 메인 프로그램을 시작한다.
//메인 스레드 우선순위 값을 출력한후,활용가능 한 모든 코어에서 두 스레드를 실행한다.
//연산 코어가 하나 이상이 있다면, 2초 안에 첫 결과를 얻는다.
//가장 높은 우선순위인 스레드는 보통 더 반복해서 계산 해야한다.
//다만, 두값이 서로 가까워야 한다. 하지만 어떤 다른 프로그램이
//모든 CPU 코어를 적재해 실행하고 있을 때는 상황이 상당히 달라질수 있다.
Console.WriteLine("Current thread priority: {0}", Thread.CurrentThread.Priority);
Console.WriteLine("Running on all cores available");
RunThreads();
Console.WriteLine("Running on a single core");
//이상황을 재연하기 위해 운영체제가 단일 코거 (번호1)에서 모든 스레드를 싱행하도록 지시하는
//.ProcessorAffinity 옵션을 설정한다.
//지금 결과가 아주 달라져야 하며, 계산에만 2초이상이 걸린다.
//이런 일이 발생하는 이유는 CPU 코어가 높은 우선순위를 갖는 스레드를 대부분 실행하되, 나머지 스레드에 매우 적은 시간을 주기 때문이다.
//운영체제가 스레드에 어떻게 우선수위를 매기는지 보여주는것에 주목하길 바란다.
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1);
RunThreads();
}
static void RunThreads()
{
var sample = new ThreadSample();
var threadOne = new Thread(sample.CountNumbers);
var threadTwo = new Thread(sample.CountNumbers);
//첫 번째 스레드는 가장 높은 우선 순위인 ThreadPriority.Highest를 갖는 반면에
threadOne.Priority = ThreadPriority.Highest;
//두번째 스레드는 가장 낮은 threadTwo.Priority = ThreadPriority.Lowest;를 갖는다
threadTwo.Priority = ThreadPriority.Lowest;
}
class ThreadSample
{
private bool _isStopped = false;
public void Stop()
{
_isStopped = true;
}
public void CountNumbers()
{
long counter = 0;
while (!_isStopped)
{
counter++;
}
Console.WriteLine("{0} with {1,11} priority " +
Thread.CurrentThread.Priority,
counter.ToString("N0"));
}
}
}
결과
![](https://blog.kakaocdn.net/dn/kQQ3l/btqDWV087iB/Ic7E3XlxuHrba3kD64IvBK/img.png)
728x90
'[2-3]operating system > [2-3.2]Thread' 카테고리의 다른 글
[Thread Book #4 ] 스레드 중단 (0) | 2020.06.13 |
---|---|
스레드 동기화 (0) | 2020.06.13 |
[Thread Book #5] 스레드 상태 조사 (0) | 2020.06.12 |
스레드의 파라미터 전달 (0) | 2020.05.13 |
Using WaitingBar with a Background Worker | UI for WinForms Documentation | Telerik UI for WinForms (0) | 2020.02.18 |
댓글