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)
13030정성태4/15/20226495오류 유형: 804. 정규 표현식 오류 - Quantifier {x,y} following nothing.
13029정성태4/14/20226899Windows: 203. iisreset 후에도 이전에 설정한 전역 환경 변수가 w3wp.exe에 적용되는 문제
13028정성태4/13/20226808.NET Framework: 1193. (appsettings.json처럼) web.config의 Debug/Release에 따른 설정 적용
13027정성태4/12/20227102.NET Framework: 1192. C# - 환경 변수의 변화를 알리는 WM_SETTINGCHANGE Win32 메시지 사용법파일 다운로드1
13026정성태4/11/20228633.NET Framework: 1191. C 언어로 작성된 FFmpeg Examples의 C# 포팅 전체 소스 코드 [3]
13025정성태4/11/20227965.NET Framework: 1190. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 vaapi_encode.c, vaapi_transcode.c 예제 포팅
13024정성태4/7/20226459.NET Framework: 1189. C# - 런타임 환경에 따라 달라진 AppDomain.GetCurrentThreadId 메서드
13023정성태4/6/20226765.NET Framework: 1188. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcoding.c 예제 포팅 [3]
13022정성태3/31/20226667Windows: 202. 윈도우 11 업그레이드 - "PC Health Check"를 통과했지만 여전히 업그레이드가 안 되는 경우 해결책
13021정성태3/31/20226839Windows: 201. Windows - INF 파일을 이용한 장치 제거 방법
13020정성태3/30/20226577.NET Framework: 1187. RDP 접속 시 WPF UserControl의 Unloaded 이벤트 발생파일 다운로드1
13019정성태3/30/20226574.NET Framework: 1186. Win32 Message를 Code로부터 메시지 이름 자체를 구하고 싶다면?파일 다운로드1
13018정성태3/29/20227116.NET Framework: 1185. C# - Unsafe.AsPointer가 반환한 포인터는 pinning 상태일까요? [5]
13017정성태3/28/20226916.NET Framework: 1184. C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법 - 두 번째 이야기 [3]
13016정성태3/27/20227768.NET Framework: 1183. C# 11에 추가된 ref 필드의 (우회) 구현 방법파일 다운로드1
13015정성태3/26/20229122.NET Framework: 1182. C# 11 - ref struct에 ref 필드를 허용 [1]
13014정성태3/23/20227693VC++: 155. CComPtr/CComQIPtr과 Conformance mode 옵션의 충돌 [1]
13013정성태3/22/20226025개발 환경 구성: 641. WSL 우분투 인스턴스에 파이썬 2.7 개발 환경 구성하는 방법
13012정성태3/21/20225348오류 유형: 803. C# - Local '...' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
13011정성태3/21/20226826오류 유형: 802. 윈도우 운영체제에서 웹캠 카메라 인식이 안 되는 경우
13010정성태3/21/20225751오류 유형: 801. Oracle.ManagedDataAccess.Core - GetTypes 호출 시 "Could not load file or assembly 'System.DirectoryServices.Protocols...'" 오류
13009정성태3/20/20227380개발 환경 구성: 640. docker - ibmcom/db2 컨테이너 실행
13008정성태3/19/20226673VS.NET IDE: 176. 비주얼 스튜디오 - 솔루션 탐색기에서 프로젝트를 선택할 때 csproj 파일이 열리지 않도록 만드는 방법
13007정성태3/18/20226259.NET Framework: 1181. C# - Oracle.ManagedDataAccess의 Pool 및 그것의 연결 개체 수를 알아내는 방법파일 다운로드1
13006정성태3/17/20227335.NET Framework: 1180. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 remuxing.c 예제 포팅
13005정성태3/17/20226199오류 유형: 800. C# - System.InvalidOperationException: Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.
... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...