Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1195. C# - Thread.Yield와 Thread.Sleep(0)의 차이점(?) [링크 복사], [링크+제목 복사],
조회: 15213
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)
(시리즈 글이 4개 있습니다.)
.NET Framework: 914. C# - Task.Yield 사용법
; https://www.sysnet.pe.kr/2/0/12241

.NET Framework: 916. C# - Task.Yield 사용법 (2)
; https://www.sysnet.pe.kr/2/0/12245

.NET Framework: 1163.  C# - 윈도우 환경에서 usleep을 호출하는 방법
; https://www.sysnet.pe.kr/2/0/12980

.NET Framework: 1195. C# - Thread.Yield와 Thread.Sleep(0)의 차이점(?)
; https://www.sysnet.pe.kr/2/0/13033




C# - Thread.Yield와 Thread.Sleep(0)의 차이점(?)

예전 글에서,

(번역글) .NET Internals Cookbook Part 10 - Threads, Tasks, asynchronous code and others
67. Thread.Yield와 Thread.Sleep(0)의 차이점
; https://www.sysnet.pe.kr/2/0/11879#67

이에 대해 설명을 했는데, 그때 테스트가 잘못돼 다시 설명을 합니다. ^^;




자, 우선, Yield는 "현재 프로세서에 ready 상태의 스레드가 있는지 체크 후 있으면 해당 스레드로 전환이 되지만 없으면 현재 스레드가 계속 실행"하는 것을 테스트해보겠습니다.

이를 위해 다음과 같이 코드를 작성하고,

using System;
using System.Diagnostics;
using System.Numerics;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        static int _processorId = 1;

        static void Main(string[] args)
        {
            Thread t1 = new Thread(yieldProc);
            Thread t2 = new Thread(lowPriorityProc);
            Thread t3 = new Thread(lowPriorityProc);

            t3.Start();
            t2.Start();
            t1.Start();
            t1.Join();
            t2.Join();
        }

        private static void lowPriorityProc()
        {
            SetProcessAffinity(_processorId);

            Console.WriteLine("lowPriorityProc: " + AppDomain.GetCurrentThreadId());
            Thread.CurrentThread.Priority = ThreadPriority.Lowest;

            int i = 0;
            BigInteger sum = new BigInteger();

            while (true)
            {
                i++;
                sum += i;
            }
        }

        private static void yieldProc()
        {
            SetProcessAffinity(_processorId);

            Console.WriteLine("yieldProc: " + AppDomain.GetCurrentThreadId());
            while (true)
            {
                Thread.Yield();
            }
        }

        // https://www.sysnet.pe.kr/2/0/10933
        static void SetProcessAffinity(int cpuNumber)
        {
            if (cpuNumber >= Environment.ProcessorCount)
            {
                cpuNumber = 0;
            }

            foreach (ProcessThread pthread in Process.GetCurrentProcess().Threads)
            {
                if (pthread.Id == AppDomain.GetCurrentThreadId()) // .NET Framework에서만!
                {
                    pthread.ProcessorAffinity = new IntPtr(1 << cpuNumber);
                    break;
                }
            }
        }
    }
}

실행하면 이런 결과가 나올 텐데요,

lowPriorityProc: 65544
lowPriorityProc: 21836
yieldProc: 45984

이때 Process Explorer를 이용해 "yieldProc"으로 지정된 45984 스레드를 찾아보면 CPU 값이 (24 코어에서) "0.01" 정도로 나오는 것을 확인할 수 있습니다. 왜냐하면, 같은 CPU에 실행 중인 lowPriorityProc 스레드 2개가 더 있기 때문에 Yield는 그 스레드로 계속해서 실행을 양보하기 때문에 (1/n도 아닌 더욱) 낮은 CPU 사용량만을 보이는 것입니다. (또한, 위의 코드에서 lowPriorityProc의 우선순위가 ThreadPriority.Lowest로 설정되었는데도 CPU 양보를 하고 있다는 것을 알 수 있습니다.)

반면, lowPriorityProc에서 SetProcessAffinity 호출을 제거하면,

private static void lowPriorityProc()
{
    // SetProcessAffinity(_processorId);

    Console.WriteLine("lowPriorityProc: " + AppDomain.GetCurrentThreadId());
    Thread.CurrentThread.Priority = ThreadPriority.Lowest;

    // ...[생략]...
}

이제는 yieldProc 스레드가 실행 중인 CPU를 lowPriorityProc 스레드에서 점유하지 않으므로, 이제 yieldProc은 CPU 100% 현상을 보이게 됩니다. 위에서 설명한 그대로 현상이 재현된 것입니다.

자, 그럼 Sleep(0)을 검증해 볼까요?

다시 위의 첫 번째 예제에서 단지 yieldProc의 내부만 Sleep 호출로 바꾼 후,

private static void yieldProc()
{
    SetProcessAffinity(_processorId);

    Console.WriteLine("yieldProc: " + AppDomain.GetCurrentThreadId());
    while (true)
    {
        // Thread.Yield();
        Thread.Sleep(0);
    }
}

실행하면, Process Explorer에서 yieldProc의 스레드는 lowPriorityProc의 스레드보다 우선순위가 높게 설정돼 있으므로 양보를 하지 말아야 합니다. 하지만, 실제로 실행해 보면 Yield처럼 낮은 CPU 사용량을 보입니다. 즉, 양보를 하고 있는 것입니다.

역시나, 이번에도 테스트상으로는 Yield와 Sleep(0)의 차이점을 알 수가 없습니다. ^^;

결국, Yield와 Sleep(0)은 경우에 따라 CPU 사용량이 (같은 CPU를 사용하는 다른 스레드가 있다면 1/n보다) 낮을 수도 있고, (같은 CPU를 사용하는 다른 스레드가 없다면) 높을 수도 있습니다. 또한 Yield/Sleep 모두, (스레드의 우선순위에 상관없이) 같은 CPU를 사용하는 다른 스레드가 있다면 1/n 사용량을 확보하진 못합니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/18/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 76  77  [78]  79  80  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11986정성태7/17/201916884오류 유형: 557. 드라이브 문자를 할당하지 않은 파티션을 탐색기에서 드라이브 문자와 함께 보여주는 문제
11985정성태7/17/201917031개발 환경 구성: 452. msbuild - csproj에 환경 변수 조건 사용 [1]
11984정성태7/9/201925557개발 환경 구성: 451. Microsoft Edge (Chromium)을 대상으로 한 Selenium WebDriver 사용법 [1]
11983정성태7/8/201914903오류 유형: 556. nodemon - 'mocha' is not recognized as an internal or external command, operable program or batch file.
11982정성태7/8/201914993오류 유형: 555. Visual Studio 빌드 오류 - result: unexpected exception occured (-1002 - 0xfffffc16)
11981정성태7/7/201918076Math: 64. C# - 3층 구조의 신경망(분류)파일 다운로드1
11980정성태7/7/201928183개발 환경 구성: 450. Visual Studio Code의 Java 확장을 이용한 간단한 프로젝트 구축파일 다운로드1
11979정성태7/7/201918447개발 환경 구성: 449. TFS에서 gitlab/github등의 git 서버로 마이그레이션하는 방법
11978정성태7/6/201917688Windows: 161. 계정 정보가 동일하지 않은 PC 간의 인증을 수행하는 방법 [1]
11977정성태7/6/201922291오류 유형: 554. git push - error: RPC failed; HTTP 413 curl 22 The requested URL returned error: 413 Request Entity Too Large
11976정성태7/4/201916635오류 유형: 553. (잘못 인증 한 후) 원격 git repo 재인증 시 "remote: HTTP Basic: Access denied" 오류 발생
11975정성태7/4/201925434개발 환경 구성: 448. Visual Studio Code에서 콘솔 응용 프로그램 개발 시 "입력"받는 방법
11974정성태7/4/201921174Linux: 22. "Visual Studio Code + Remote Development"로 윈도우 환경에서 리눅스(CentOS 7) C/C++ 개발
11973정성태7/4/201919911Linux: 21. 리눅스에서 공유 라이브러리가 로드되지 않는다면?
11972정성태7/3/201923712.NET Framework: 847. JAVA와 .NET 간의 AES 암호화 연동 [1]파일 다운로드1
11971정성태7/3/201919986개발 환경 구성: 447. Visual Studio Code에서 OpenCvSharp 개발 환경 구성
11970정성태7/2/201918582오류 유형: 552. 웹 브라우저에서 파일 다운로드 후 "Running security scan"이 끝나지 않는 문제
11969정성태7/2/201919049Math: 63. C# - 3층 구조의 신경망파일 다운로드1
11968정성태7/1/201925745오류 유형: 551. Visual Studio Code에서 Remote-SSH 연결 시 "Opening Remote..." 단계에서 진행되지 않는 문제 [1]
11967정성태7/1/201919794개발 환경 구성: 446. Synology NAS를 Windows 10에서 iSCSI로 연결하는 방법
11966정성태6/30/201918739Math: 62. 활성화 함수에 따른 뉴런의 출력을 그리드 맵으로 시각화파일 다운로드1
11965정성태6/30/201919337.NET Framework: 846. C# - 2차원 배열을 1차원 배열로 나열하는 확장 메서드파일 다운로드1
11964정성태6/30/201920891Linux: 20. C# - Linux에서의 Named Pipe를 이용한 통신
11963정성태6/29/201920627Linux: 19. C# - .NET Core Unix Domain Socket 사용 예제
11962정성태6/27/201918300Math: 61. C# - 로지스틱 회귀를 이용한 선형분리 불가능 문제의 분류파일 다운로드1
11961정성태6/27/201917829Graphics: 37. C# - PLplot - 출력 모음(Family File Output)
... 76  77  [78]  79  80  81  82  83  84  85  86  87  88  89  90  ...