Microsoft MVP성태의 닷넷 이야기
닷넷: 2311. C# - Windows / Linux 환경에서 Native Thread ID 가져오기 [링크 복사], [링크+제목 복사],
조회: 7218
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

(시리즈 글이 5개 있습니다.)
.NET Framework: 308. .NET System.Threading.Thread 개체에서 Native Thread Id를 구할 수 있을까?
; https://www.sysnet.pe.kr/2/0/1244

.NET Framework: 452. .NET System.Threading.Thread 개체에서 Native Thread Id를 구하는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/1724

.NET Framework: 1189. C# - 런타임 환경에 따라 달라진 AppDomain.GetCurrentThreadId 메서드
; https://www.sysnet.pe.kr/2/0/13024

닷넷: 2311. C# - Windows / Linux 환경에서 Native Thread ID 가져오기
; https://www.sysnet.pe.kr/2/0/13814

닷넷: 2312. C#, C++ - Windows / Linux 환경의 Thread Name 설정
; https://www.sysnet.pe.kr/2/0/13816




C# - Windows / Linux 환경에서 Native Thread ID 가져오기

.NET Framework 시절에는 AppDomain.GetCurrentThreadId로도 구할 수 있었지만,

C# - 런타임 환경에 따라 달라진 AppDomain.GetCurrentThreadId 메서드
; https://www.sysnet.pe.kr/2/0/13024

.NET Core/5+로 넘어오면서 일단 BCL 수준에서 제공하는 기능은 없어졌습니다. 어쩔 수 없이 이런 경우 P/Invoke를 사용해야 하는데, 다중 플랫폼을 위해 다음과 같은 정도로 작성하시면 됩니다.

using System.Runtime.InteropServices;

public enum LinuxSysCall
{
    __NR_gettid = 186,
}

internal class Program
{
    [DllImport("kernel32.dll")]
    public static extern uint GetCurrentThreadId();

    [DllImport("libc.so.6")]
    public static extern int syscall(int callNumber, IntPtr data);

    public static uint GetThreadNativeId()
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            return GetCurrentThreadId();
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            return (uint)syscall((int)LinuxSysCall.__NR_gettid, IntPtr.Zero);
        }

        return 0;
    }

    static void Main(string[] args)
    {
        Console.WriteLine($"CurrentThreadId: {GetThreadNativeId()}");

        ThreadPool.QueueUserWorkItem((arg) =>
        {
            uint thread_id = GetThreadNativeId();
            Console.WriteLine($"{Environment.ProcessId}, {thread_id}, {Thread.CurrentThread.Name}");
        });

        Thread.Sleep(1000);
    }
}

참고로, 위에서 syscall을 통해 gettid를 호출했는데요, syscall이 아닌 gettid를 직접 사용해도 무방합니다.

[DllImport("libc.so.6")]
public static extern int gettid();

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




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







[최초 등록일: ]
[최종 수정일: 11/14/2024]

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13805정성태11/8/20246100오류 유형: 931. Active Directory의 adprep 또는 복제가 안 되는 경우
13804정성태11/7/20248372Linux: 101. eBPF 함수의 인자를 다루는 방법
13803정성태11/7/20247770닷넷: 2309. C# - .NET Core에서 바뀐 DateTime.Ticks의 정밀도
13802정성태11/6/20248086Windows: 269. GetSystemTimeAsFileTime과 GetSystemTimePreciseAsFileTime의 차이점파일 다운로드1
13801정성태11/5/20247970Linux: 100. eBPF의 2가지 방식 - libbcc와 libbpf(CO-RE)
13800정성태11/3/20249018닷넷: 2308. C# - ICU 라이브러리를 활용한 문자열의 대소문자 변환 [2]파일 다운로드1
13799정성태11/2/20246262개발 환경 구성: 732. 모바일 웹 브라우저에서 유니코드 문자가 표시되지 않는 경우
13798정성태11/2/20248595개발 환경 구성: 731. 유니코드 - 출력 예시 및 폰트 찾기
13797정성태11/1/20248581C/C++: 185. C++ - 문자열의 대소문자를 변환하는 transform + std::tolower/toupper 방식의 문제점파일 다운로드1
13796정성태10/31/20247910C/C++: 184. C++ - ICU dll을 이용하는 예제 코드 (Windows)파일 다운로드1
13795정성태10/31/20247066Windows: 268. Windows - 리눅스 환경처럼 공백으로 끝나는 프롬프트 만들기
13794정성태10/30/20247156닷넷: 2307. C# - 윈도우에서 한글(및 유니코드)을 포함한 콘솔 프로그램을 컴파일 및 실행하는 방법
13793정성태10/28/20247126C/C++: 183. C++ - 윈도우에서 한글(및 유니코드)을 포함한 콘솔 프로그램을 컴파일 및 실행하는 방법
13792정성태10/27/20246361Linux: 99. Linux - 프로세스의 실행 파일 경로 확인
13791정성태10/27/20246755Windows: 267. Win32 API의 A(ANSI) 버전은 DBCS를 사용할까요?파일 다운로드1
13790정성태10/27/20246220Linux: 98. Ubuntu 22.04 - 리눅스 커널 빌드 및 업그레이드
13789정성태10/27/20247375Linux: 97. menuconfig에 CONFIG_DEBUG_INFO_BTF, CONFIG_DEBUG_INFO_BTF_MODULES 옵션이 없는 경우
13788정성태10/26/20245807Linux: 96. eBPF (bpf2go) - fentry, fexit를 이용한 트레이스
13787정성태10/26/20247780개발 환경 구성: 730. github - Linux 커널 repo를 윈도우 환경에서 git clone하는 방법 [1]
13786정성태10/26/20247295Windows: 266. Windows - 대소문자 구분이 가능한 파일 시스템
13785정성태10/23/20246406C/C++: 182. 윈도우가 운영하는 2개의 Code Page파일 다운로드1
13784정성태10/23/20247071Linux: 95. eBPF - kprobe를 이용한 트레이스
13783정성태10/23/20246760Linux: 94. eBPF - vmlinux.h 헤더 포함하는 방법 (bpf2go에서 사용)
13782정성태10/23/20246185Linux: 93. Ubuntu 22.04 - 커널 이미지로부터 커널 함수 역어셈블
13781정성태10/22/20246986오류 유형: 930. WSL + eBPF: modprobe: FATAL: Module kheaders not found in directory
13780정성태10/22/20248193Linux: 92. WSL 2 - 커널 이미지로부터 커널 함수 역어셈블
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...