Microsoft MVP성태의 닷넷 이야기
닷넷: 2311. C# - Windows / Linux 환경에서 Native Thread ID 가져오기 [링크 복사], [링크+제목 복사],
조회: 5287
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 31  [32]  33  34  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
13137정성태10/8/202214112.NET Framework: 2055. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 닷넷 모듈을 추출하는 방법
13136정성태10/7/202214486.NET Framework: 2054. .NET Core/5+ SDK 설치 없이 dotnet-dump 사용하는 방법
13135정성태10/5/202215005.NET Framework: 2053. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프를 분석하는 방법 - 두 번째 이야기 [1]
13134정성태10/4/202212206오류 유형: 820. There is a problem with AMD Radeon RX 5600 XT device. For more information, search for 'graphics device driver error code 31'
13133정성태10/4/202213348Windows: 211. Windows - (commit이 아닌) reserved 메모리 사용량 확인 방법 [1]
13132정성태10/3/202213378스크립트: 42. 파이썬 - latexify-py 패키지 소개 - 함수를 mathjax 식으로 표현
13131정성태10/3/202217186.NET Framework: 2052. C# - Windows Forms의 데이터 바인딩 지원(DataBinding, DataSource) [2]파일 다운로드1
13130정성태9/28/202212999.NET Framework: 2051. .NET Core/5+ - 에러 로깅을 위한 Middleware가 동작하지 않는 경우파일 다운로드1
13129정성태9/27/202213615.NET Framework: 2050. .NET Core를 IIS에서 호스팅하는 경우 .NET Framework CLR이 함께 로드되는 환경
13128정성태9/23/202216549C/C++: 158. Visual C++ - IDL 구문 중 "unsigned long"을 인식하지 못하는 #import [1]파일 다운로드1
13127정성태9/22/202214809Windows: 210. WSL에 systemd 도입
13126정성태9/15/202215334.NET Framework: 2049. C# 11 - 정적 메서드에 대한 delegate 처리 시 cache 적용
13125정성태9/14/202215749.NET Framework: 2048. C# 11 - 구조체 필드의 자동 초기화(auto-default structs)
13124정성태9/13/202215517.NET Framework: 2047. Golang, Python, C#에서의 CRC32 사용
13123정성태9/8/202215568.NET Framework: 2046. C# 11 - 멤버(속성/필드)에 지정할 수 있는 required 예약어 추가
13122정성태8/26/202215992.NET Framework: 2045. C# 11 - 메서드 매개 변수에 대한 nameof 지원
13121정성태8/23/202212401C/C++: 157. Golang - 구조체의 slice 필드를 Reflection을 이용해 변경하는 방법
13120정성태8/19/202215982Windows: 209. Windows NT Service에서 UI를 다루는 방법 [3]
13119정성태8/18/202215129.NET Framework: 2044. .NET Core/5+ 프로젝트에서 참조 DLL이 보관된 공통 디렉터리를 지정하는 방법
13118정성태8/18/202212672.NET Framework: 2043. WPF Color의 기본 색 영역은 (sRGB가 아닌) scRGB [2]
13117정성태8/17/202216323.NET Framework: 2042. C# 11 - 파일 범위 내에서 유효한 타입 정의 (File-local types)파일 다운로드1
13116정성태8/4/202216772.NET Framework: 2041. C# - Socket.Close 시 Socket.Receive 메서드에서 예외가 발생하는 문제파일 다운로드1
13115정성태8/3/202217333.NET Framework: 2040. C# - ValueTask와 Task의 성능 비교 [1]파일 다운로드1
13114정성태8/2/202217218.NET Framework: 2039. C# - Task와 비교해 본 ValueTask 사용법파일 다운로드1
13113정성태7/31/202216692.NET Framework: 2038. C# 11 - Span 타입에 대한 패턴 매칭 (Pattern matching on ReadOnlySpan<char>)
13112정성태7/30/202217569.NET Framework: 2037. C# 11 - 목록 패턴(List patterns) [1]파일 다운로드1
... 31  [32]  33  34  35  36  37  38  39  40  41  42  43  44  45  ...