Microsoft MVP성태의 닷넷 이야기
.NET Framework: 571. C# - 스레드 선호도(Thread Affinity) 지정하는 방법 [링크 복사], [링크+제목 복사],
조회: 23445
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 6개 있습니다.)

C# - 스레드 선호도(Thread Affinity) 지정하는 방법

다음의 질문이 있군요. ^^

멀티코어 스레드 문의
; https://www.sysnet.pe.kr/3/0/4712

C#에서 Thread에 대해 CPU 선호도를 지정하는 방법은 간단하게 관련 Win32 API에 대한 PInvoke를 사용할 수도 있습니다.

SetThreadAffinityMask function
; https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setthreadaffinitymask

SetThreadIdealProcessor function
; https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreadidealprocessor

하지만, 가능하다면 닷넷 BCL 레벨에서 끝내는 것이 더 좋겠죠? ^^ 그래서 다음과 같이 코딩을 해줄 수 있습니다.

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread t1 = new Thread((e) =>
            {
                SetIdealProcessor(3);

                Console.WriteLine(AppDomain.GetCurrentThreadId());
                Console.ReadLine();
            });

            t1.Start();
        }

        // 이 코드는 닷넷 프레임워크 환경에서 테스트한 것입니다. (참고: 닷넷 런타임에 따라 달라지는 AppDomain.GetCurrentThreadId의 반환값)

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

            foreach (ProcessThread pthread in Process.GetCurrentProcess().Threads)
            {
                if (pthread.Id == AppDomain.GetCurrentThreadId())
                {
                    // Ideal 설정만 필요하다면?
                    // pthread.IdealProcessor = cpuNumber;

                    // Affinity 설정까지 필요하다면?
                    pthread.ProcessorAffinity = new IntPtr(1 << (cpuNumber));
                    break;
                }
            }
        }
    }
}

위의 코드를 수행하고, 화면에 출력된 스레드 ID를 Process Explorer에서 찾아 제대로 설정되었는지 확인할 수 있습니다.

cs_thread_affinity_1.png

(첨부한 코드는 이 글의 예제를 포함합니다.)




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

[연관 글]






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

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

비밀번호

댓글 작성자
 



2016-04-06 04시31분
[차가워] 안녕하세요

스레드스타트 하기 전에 프로세스를 먼저 지정해야 하는건가요?
[guest]
2016-04-06 04시41분
[차가워] AppDomain.GetCurrentThreadId() <-- 이거는 사용되지 않습니다라는 오류 문구가 나오는데 그냥 무시하면 되는건가요?
닷넷 4.5에서 위 코드를 사용해 볼가해서요
감사합니다
[guest]
2016-04-06 08시46분
[차가워] AppDomain.GetCurrentThreadId() <-- 대신에
Process.GetCurrentProcess().Threads[0].Id <-- 이거를 사용하면 될거 같네요
[guest]
2016-04-06 10시41분
스레드 구분이 가능하다면 Process.GetCurrentProcess().Threads[...n...].Id 를 쓰는 것이 더 좋습니다.

AppDomain.GetCurrentThreadId의 경우 4.5에서도 지원됩니다. (단지 obsolete 경고가 뜨는데 현재까지는 무시할 수 있습니다.)
정성태
2016-04-06 10시43분
"스레드스타트 하기 전에 프로세스를 먼저 지정해야 하는건가요?" 질문에 대한 해답은 이미 코드에 있습니다.
정성태
2016-04-06 04시50분
[차가워] 정말 감사합니다
구벅
[guest]
2019-03-12 04시50분
[ㅇㅇ] IdealProcessor라는 것이 CPU에 코어와 대응되는 개념인가요? CPU가 4코어짜리면, IdealProcessor를 3으로 설정하면 4번쨰코어에 스레드가 할당이 되는 것인가요?
[guest]
2019-03-12 07시24분

정성태

... 61  62  63  64  65  66  67  68  69  70  71  [72]  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
11835정성태3/5/201914062.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201912947개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201913696개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201910754오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201910297오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201910143오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201912032개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201918421개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201912341오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201912242오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201917098개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201911908오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201913364오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201911520오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201911999오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201915109오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201913777Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201912699VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/20199898오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201912365Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201911268오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201910053오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201911666.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/20199550오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201913268오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
11810정성태2/11/201911344.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
... 61  62  63  64  65  66  67  68  69  70  71  [72]  73  74  75  ...