Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

윈도우 - 싱글 스레드는 컨텍스트 스위칭이 없을까요?

아래와 같은 질문이 있군요. ^^

싱글스레드 프로그램도 컨텍스트 스위칭이 생길 수 있나요?
; https://www.sysnet.pe.kr/3/0/5755

답글에서도 언급했지만, 스레드가 컨텍스트 스위칭이 발생하는가에 대해서는 "싱글"이냐, "멀티"냐가 중요한 것이 아닙니다. 그건 운영체제의 스레드 스케줄링이 결정할 사항입니다.

그렇다면, 단순히 무한 루프를 도는 스레드가 정말 다른 코어에서 실행되는지 확인해 볼까요? ^^

윈도우의 경우 GetCurrentProcessorNumber API를 이용하면,

GetCurrentProcessorNumber function (processthreadsapi.h)
; https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentprocessornumber

코드는 대략 다음과 같이 작성할 수 있습니다.

using System.Runtime.InteropServices;

internal class Program
{
    [DllImport("kernel32.dll")]
    private static extern int GetCurrentProcessorNumber();

    static void Main(string[] args)
    {
        HashSet<int> list = new HashSet<int>();

        while (true)
        {
            int coreIdx = GetCurrentProcessorNumber();
            if (list.Contains(coreIdx) == false)
            {
                list.Add(coreIdx);
                Console.WriteLine($"[{DateTime.Now:T}] {coreIdx}");
            }
        }
    }
}

16개 코어를 가진 제 컴퓨터에서 실행해 보면 이런 결과를 얻게 됩니다.

[오후 7:43:34] 2
[오후 7:43:34] 15
[오후 7:43:34] 0
[오후 7:43:34] 3
[오후 7:43:34] 4
[오후 7:43:35] 1
[오후 7:43:35] 5
[오후 7:43:35] 8
[오후 7:43:35] 7
[오후 7:43:35] 13
[오후 7:43:35] 11
[오후 7:43:35] 12
[오후 7:43:35] 6
[오후 7:43:36] 10
[오후 7:43:36] 14
[오후 7:43:36] 9

2초도 안 돼서, 단일 스레드의 무한 루프가 16개의 코어 모두에서 실행된 것을 알 수 있습니다.

만약 이런 결과가 싫다면, C# - IdealProcessor와 ProcessorAffinity의 차이점 글에서 설명한 대로 ProcessorAffinity를 지정하면 됩니다.

using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;

[assembly: SupportedOSPlatform("windows")]

internal class Program
{
    [DllImport("kernel32.dll")]
    private static extern int GetCurrentProcessorNumber();
    [DllImport("kernel32.dll")]
    static extern long GetCurrentThreadId();

    static void Main(string[] args)
    {
        HashSet<int> list = new HashSet<int>();
        SetIdealProcessor(3);

        while (true)
        {
            // ...[생략]...
        }
    }

    static void SetIdealProcessor(int cpuNumber)
    {
        if (cpuNumber >= Environment.ProcessorCount)
        {
            cpuNumber = 0;
        }

        foreach (ProcessThread pthread in Process.GetCurrentProcess().Threads)
        {
            if (pthread.Id == GetCurrentThreadId())
            {
                pthread.ProcessorAffinity = new IntPtr(1 << (cpuNumber));
                break;
            }
        }
    }
}

위의 프로그램을 실행하면, 이제 "3"만 출력되고 다른 코어의 숫자는 볼 수 없습니다.

[오후 7:49:55] 3

그런데, 여기서 오해하면 안 되는 사실이 있는데요, 위와 같이 1개의 코어에 고정이 되었다고 해서 context switching이 없는 것은 아닙니다. 이것은 Process Explorer와 같은 도구를 이용해 확인할 수 있는데요,

thread_ctx_switch_1.png

그러니까, 1개의 코어라고 해도 해당 스레드가 실행될 quantum 시간을 소비했으면 다른 스레드에 양보를 하게 됩니다. 따라서 현재의 스레드 문맥이 저장되고, 이후 다시 스케줄링 되면 문맥이 복원돼 실행을 계속합니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/24/2022]

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

비밀번호

댓글 작성자
 




... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13181정성태12/3/20224768Linux: 54. 리눅스/WSL - hello world 어셈블리 코드 x86/x64 (nasm)
13180정성태12/2/20224946.NET Framework: 2074. C# - 스택 메모리에 대한 여유 공간 확인하는 방법파일 다운로드1
13179정성태12/2/20224367Windows: 216. Windows 11 - 22H2 업데이트 이후 Terminal 대신 cmd 창이 뜨는 경우
13178정성태12/1/20224870Windows: 215. Win32 API 금지된 함수 - IsBadXxxPtr 유의 함수들이 안전하지 않은 이유파일 다운로드1
13177정성태11/30/20225599오류 유형: 829. uwsgi 설치 시 fatal error: Python.h: No such file or directory
13176정성태11/29/20224519오류 유형: 828. gunicorn - ModuleNotFoundError: No module named 'flask'
13175정성태11/29/20226146오류 유형: 827. Python - ImportError: cannot import name 'html5lib' from 'pip._vendor'
13174정성태11/28/20224713.NET Framework: 2073. C# - VMMap처럼 스택 메모리의 reserve/guard/commit 상태 출력파일 다운로드1
13173정성태11/27/20225402.NET Framework: 2072. 닷넷 응용 프로그램의 스레드 스택 크기 변경
13172정성태11/25/20225209.NET Framework: 2071. 닷넷에서 ESP/RSP 레지스터 값을 구하는 방법파일 다운로드1
13171정성태11/25/20224825Windows: 214. 윈도우 - 스레드 스택의 "red zone"
13170정성태11/24/20225138Windows: 213. 윈도우 - 싱글 스레드는 컨텍스트 스위칭이 없을까요?
13169정성태11/23/20225718Windows: 212. 윈도우의 Protected Process (Light) 보안 [1]파일 다운로드2
13168정성태11/22/20225000제니퍼 .NET: 31. 제니퍼 닷넷 적용 사례 (9) - DB 서비스에 부하가 걸렸다?!
13167정성태11/21/20225038.NET Framework: 2070. .NET 7 - Console.ReadKey와 리눅스의 터미널 타입
13166정성태11/20/20224765개발 환경 구성: 651. Windows 사용자 경험으로 WSL 환경에 dotnet 런타임/SDK 설치 방법
13165정성태11/18/20224670개발 환경 구성: 650. Azure - "scm" 프로세스와 엮인 서비스 모음
13164정성태11/18/20225570개발 환경 구성: 649. Azure - 비주얼 스튜디오를 이용한 AppService 원격 디버그 방법
13163정성태11/17/20225519개발 환경 구성: 648. 비주얼 스튜디오에서 안드로이드 기기 인식하는 방법
13162정성태11/15/20226590.NET Framework: 2069. .NET 7 - AOT(ahead-of-time) 컴파일
13161정성태11/14/20225813.NET Framework: 2068. C# - PublishSingleFile로 배포한 이미지의 역어셈블 가능 여부 (난독화 필요성) [4]
13160정성태11/11/20225757.NET Framework: 2067. C# - PublishSingleFile 적용 시 native/managed 모듈 통합 옵션
13159정성태11/10/20228977.NET Framework: 2066. C# - PublishSingleFile과 관련된 옵션 [3]
13158정성태11/9/20225233오류 유형: 826. Workload definition 'wasm-tools' in manifest 'microsoft.net.workload.mono.toolchain' [...] conflicts with manifest 'microsoft.net.workload.mono.toolchain.net7'
13157정성태11/8/20225901.NET Framework: 2065. C# - Mutex의 비동기 버전파일 다운로드1
13156정성태11/7/20226805.NET Framework: 2064. C# - Mutex와 Semaphore/SemaphoreSlim 차이점파일 다운로드1
... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...