Microsoft MVP성태의 닷넷 이야기
.NET Framework: 312. Native 스레드와 Managed 스레드 개체의 상태 관계 [링크 복사], [링크+제목 복사],
조회: 25501
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

Native 스레드와 Managed 스레드 개체의 상태 관계

네이티브에서는 CreateThread Win32 API로 얻은 HANDLE 개체를 이용해서 스레드를 제어할 수 있고, 닷넷에서는 그와 같은 역할을 System.Threading.Thread 타입을 이용해서 할 수 있습니다.

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

Thread Class
; https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread

* 대부분의 닷넷 타입들이 static 메서드에 대해서만 "Thread Safety"한데, 
  Thread 타입의 경우 드물게 인스턴스 메서드에 대해서도 "Thread Safety"한 특징이 있습니다.

실제로 지난번 글에서 Thread 인스턴스에서는 Native Thread Id를 구해오는 것조차 쉽지 않음을 보여드렸는데요.

.NET System.Threading.Thread 개체에서 Native Thread Id를 구할 수 있을까?
; https://www.sysnet.pe.kr/2/0/1244

그럼에도 불구하고 제가 스레드의 Naitve/Managed 상태에 대해서 관심을 갖게 된 것은 ".NET에서 다른 스레드의 콜 스택 덤프"를 뜨는 방법을 찾는 것에서 시작되었습니다.

.NET 스레드 콜 스택 덤프 (1) - 다른 스레드의 스택 덤프 구하는 방법
; https://www.sysnet.pe.kr/2/0/802

그리고, 위의 방법에 대한 문제점을 그다음 글에서 언급을 했었는데요.

.NET 스레드 콜 스택 덤프 (2) - Managed Stack Explorer 소스 코드를 이용한 스택 덤프 구하는 방법
; https://www.sysnet.pe.kr/2/0/1162

bool suspend = false;
if ((newThread.ThreadState & System.Threading.ThreadState.Suspended) != System.Threading.ThreadState.Suspended)
{
    newThread.Suspend();
    suspend = true;
}

DoCallStack();

if (suspend == true)
{
    newThread.Resume();
}

if 문을 실행했을 때와 Suspend를 실행한 시점이 하나의 동기화 단위로 묶이지 않기 때문에 상태가 엇갈릴 수 있음을 설명드렸습니다.

이번 글은, 위의 문제를 해결하려고 Native 스레드를 건드리면서 알게 된 정보를 공유해 보는 것입니다.




아실 지 모르지만, Win32 API에서의 Resume/Suspend 메서드는 호출 횟수가 카운팅이 된다는 특징이 있습니다.

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

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

즉, SuspendThread를 2번 호출했으면 ResumeThread를 2번 호출해주어야만 정상적으로 스레드가 Running 상태로 복귀하는 것입니다.

여기에서 힌트를 얻은 것이, 그렇다면 닷넷 스레드 타입에서 Suspend/Resume를 해줄 것이 아니라 Native 차원에서 해주면 혹시 '동기화 단위'로 묶이지 않은 것에 대한 문제를 해결할 수 있지 않을까... 하는 생각을 하게 된 것입니다.

하지만, 결론부터 말씀드리자면 ^^ 이것은 완전히 빗나간 예측입니다. 닷넷은, CLR 위에서 돌아가는 것이니만큼 너무나 추상화를 잘해주어서 Managed 차원에서의 Suspend/Resume은 Native 차원에서의 Suspend/Resume과 완전히 상관이 없기 때문입니다.

이에 대해 간략하게 예제 코드로 테스트 해볼까요? ^^

우선, 이전 글에서 사용한 방법을 통해서 다른 스레드의 Native Thread Id를 구하는 것에서부터 시작합니다.

bool net45 = false;
Type type = Type.GetType("System.Reflection.ReflectionContext");
if (type != null)
{
    net45 = true;
}

Thread newThread = new Thread(Run);
newThread.Start();

FieldInfo fieldInfo = typeof(Thread).GetField("DONT_USE_InternalThread", BindingFlags.NonPublic | BindingFlags.Instance);
IntPtr objValue = (IntPtr)fieldInfo.GetValue(newThread);

// .NET 4.0에서는 offset 값이 16이었지만, .NET 4.5를 설치하면 15로 바뀜.
IntPtr teb = new IntPtr(Marshal.ReadInt32(objValue, ((net45 == true) ? 15 : 16) * 4));
int clientTid = Marshal.ReadInt32(teb, 0x6b8);

세상에나... 지난번에도 말씀드렸지만 offset 값을 쓰는 것이 저렇게 위험하답니다. ^^ (.NET 4.5에서는 옵셋값이 60바이트 위치로 바뀐 것을 확인할 수 있습니다.)

Run 메서드는 다음과 같이 일단 무한 루프를 돌도록 만들었습니다.

static void Run()
{
    int idx = 0;
    while (true)
    {
        Interlocked.Increment(ref idx); // 동기화가 필요없지만... 그냥!
        System.Diagnostics.Trace.WriteLine(idx);
    }
}

자, 이제 스레드 상태를 알 수 있는 함수를 작성해야 하는데요. 우선, Managed 개체에서는 단순히 Thread.ThreadState 속성을 제공해주는 것으로 해결이 되지만, Native 스레드 상태를 알기 위해서는 다음과 같이 native thread id를 단서로 알아내는 코드를 작성할 수 있습니다.

private static void CheckThreadState(int clientTid)
{
    foreach (ProcessThread thread in Process.GetCurrentProcess().Threads)
    {
        if (thread.Id == clientTid)
        {
            Console.WriteLine("[" + clientTid + " thread] : " + thread.ThreadState);
            break;
        }
    }
}

준비는 끝났고, 이제 프로그램을 실행하고 CheckThreadState(clientTid); 코드를 이용해서 상태를 확인하면 Native 스레드는 "Running" 중임을 알 수 있습니다.

그럼 SusnepdThread 2번에 ResumeThread 한 번을 호출하고 스레드 상태를 확인해 볼까요? ^^

threadHandle = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)clientTid);
if (threadHandle == IntPtr.Zero)
{
    break;
}

CheckThreadState(clientTid); // Running

SuspendThread(threadHandle); SuspendThread(threadHandle);
ResumeThread(threadHandle);

CheckThreadState(clientTid); // Wait

아하... Wait 상태인 것으로 봐서 Suspend/Resume 짝이 맞아야 한다는 것을 테스트로 알 수 있습니다. 그래서, ResumeThread를 한번 더 호출해 주고 CheckThreadState로 확인하면 Running으로 돌아오는 것을 알 수 있습니다.

그럼, 이 상태에서 Managed 스레드 개체의 상태를 함께 출력해 볼까요?

Console.Write("System.Threading.Thread.ThreadState == " + newThread.ThreadState + ", "); // Running
CheckThreadState(clientTid); // Running

SuspendThread(threadHandle);
SuspendThread(threadHandle);
ResumeThread(threadHandle);

Console.Write("System.Threading.Thread.ThreadState == " + newThread.ThreadState + ", "); // Running
CheckThreadState(clientTid); // Wait

그렇습니다. Managed 스레드 상태는 Native 스레드 상태에 관계없이 언제나 Running 상태만을 표시하고 있습니다. 즉, Native와 Managed 간에 상태가 완전히 독립적이라는 것을 알 수 있습니다.

반대의 경우는 어떨까요? System.Threading.Thread.Suspend()를 호출한 경우, Managed 스레드 상태를 바꾸긴 하지만 실제로 그 실행을 중지시키려면 Native 스레드를 중지시켜야 하기 때문에 이번에는 정상적으로 2개의 상태가 Suspended / Wait를 각각 가리키게 됩니다.

이 때문에 Native 스레드에서 SuspendThread를 호출해 주었다고 해도 콜스택을 뜨는 System.Diagnostics.StackTrace 함수에서 확인하는 Managed 스레드의 상태가 여전히 Running이므로 ThreadStateException 예외가 발생하게 되는 것입니다.

결국 정리해 보면... System.Diagnostics.StackTrace를 이용하여 다른 Managed 스레드의 콜스택을 안전하게 얻으려면 System.Threading.Thread 개체 차원에서도 Native와 마찬가지로 Suspend/Resume에 대한 카운트가 제공되어야만 합니다. (아쉽게도, 테스트 해본 결과 System.Threading.Thread는 Suspend/Resume에 대한 카운트 관리 기능은 없습니다.)

어쨌든 현재로써는, 제가 아는 한 다른 스레드의 콜 스택을 얻는 가장 안전한 방법은 ICorDebug를 사용하는 방법뿐이 없는 것 같습니다.

.NET 스레드 콜 스택 덤프 (5) - ICorDebug 인터페이스 사용법
; https://www.sysnet.pe.kr/2/0/1249

첨부된 파일은 위의 코드를 포함한 예제 프로젝트입니다.




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

[연관 글]






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

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

비밀번호

댓글 작성자
 



2015-02-06 12시24분
Suspend­Thread는 운영체제의 스케쥴러에게 비동기적으로 신호를 보낼 뿐, Suspend­Thread 함수가 반환된 시점에 대상 스레드가 중지했다고 가정해서는 안됩니다. 이를 위한 보조 함수로 GetThreadContext를 사용할 수 있는데, 이 함수는 반드시 중지된 스레드로부터 스레드 문맥 정보를 가져오기 때문입니다.

The SuspendThread function suspends a thread, but it does so asynchronously
; https://devblogs.microsoft.com/oldnewthing/20150205-00/?p=44743

-----------------------------------------------------------------

아래의 글에서 SuspendThread의 동작에 대한 이야기가 살짝 나옵니다.

The case of the UI thread that hung in a kernel call
; https://devblogs.microsoft.com/oldnewthing/20250411-00/?p=111066

The thread does not suspend immediately, but rather waits for the kernel to finish its work, and then before returning to user mode, the kernel does a Check­For­Kernel­Apc­Delivery to see if there were any requests waiting. It picks up the request to suspend, and that is when the thread actually suspends.

그러니까, 현재 커널 코드를 실행 중인 스레드가 user-mode로 복귀할 때 (Check­For­Kernel­Apc­Delivery 함수를 호출해) APC 큐를 살펴 보게 되고, 그 안에 "suspend" 하도록 만드는 작업이 있다면 그걸 실행하게 되면서 비로소 suspended 상태로 빠지는 것입니다.

참고로, 커널 실행 중인 코드를 suspend 상태로 만들 수는 없는데, 왜냐하면 자칫 특정 kernel lock을 획득 중인 경우일 수도 있기 때문이라고.

-----------------------------------------------------------------

Why you should never suspend a thread
; https://devblogs.microsoft.com/oldnewthing/20031209-00/?p=41573

SuspendThread 사용은 Debugger를 위한 기능으로, 일반 응용 프로그램에서 사용하는 것은 바람직하지 않다는 내용의 글입니다. 일례로, 다음의 코드는 쉽게 hang에 빠지게 되는데요,

-------------------------------------
using System;
using System.Runtime.InteropServices;
using System.Threading;

class Program
{
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern void OutputDebugString(string lpOutputString);

    public static void Main()
    {
        Thread t = new Thread(new ThreadStart(Program.worker));
        t.Start();
        Console.WriteLine("Press Enter to suspend");
        Console.ReadLine();
        t.Suspend(); // .NET Framework에서만 동작 (.NET Core/5+에서는 "System.PlatformNotSupportedException: Thread suspend is not supported on this platform" 예외 발생)

        OutputDebugString("you can see this in dbgview");

        Console.WriteLine("But, you can't see this");
        Console.ReadLine();
        t.Resume();
    }
    static void worker()
    {
        for (; ; ) Console.Write("{0}\r", System.DateTime.Now);
    }
}
-------------------------------------

왜냐하면 worker를 수행하는 스레드가 끊임 없이 Console.Out 자원에 대해 lock/출력/unlock을 반복하게 되는데, 만약 unlock 시점이 아닌 상황에서 t.Suspend()로 스레드가 중지되면 Console.Out에 대한 lock이 잠긴 상태로 유지가 됩니다. 따라서, 바로 이후에 나오는 Console.WriteLine("But, you can't see this"); 코드가 worker를 수행하는 스레드가 잠갔던 Console.Out에 대한 lock이 해제될 때까지 대기하게 돼 이는 무한 대기 현상을 발생시킵니다.

이외에도, Win32 Heap도 내부적으로는 lock을 이용한 thread-safe를 보장하는데, 만약 특정 스레드가 heap 할당 중에 - 즉, heap-lock을 소유한 상태에서 Suspend가 되었다면, 이후 다른 스레드들이 heap을 필요로 해 할당하게 되는 상황이 오면 줄줄이 무한 대기 상태에 빠질 수 있습니다.
정성태

1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13693정성태7/24/20247244개발 환경 구성: 717. Visual Studio - C# 프로젝트에서 레지스트리에 등록하지 않은 COM 개체 참조 및 사용 방법파일 다운로드1
13692정성태7/24/20248026디버깅 기술: 199. Windbg - 리눅스에서 뜬 닷넷 응용 프로그램 덤프 파일에 포함된 DLL의 Export Directory 탐색
13691정성태7/23/20247385디버깅 기술: 198. Windbg - 스레드의 Win32 Message Queue 정보 조회
13690정성태7/23/20247019오류 유형: 919. Visual C++ 리눅스 프로젝트 - error : ‘u8’ was not declared in this scope
13689정성태7/22/20248526디버깅 기술: 197. Windbg - PE 포맷의 Export Directory 탐색
13688정성태7/21/20247630닷넷: 2281. C# - Lock / Wait 상태에서도 일부 Win32 메시지 처리파일 다운로드1
13687정성태7/19/20248060닷넷: 2280. C# - PostThreadMessage로 보낸 메시지를 Windows Forms에서 수신하는 방법파일 다운로드1
13686정성태7/19/20247855오류 유형: 918. Visual Studio - ATL Simple Object 추가 시 error C2065: 'IDR_...': undeclared identifier
13685정성태7/19/20248002스크립트: 66. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법 - 두 번째 이야기
13684정성태7/19/20248181닷넷: 2279. C# - 문자열 보간식 사례 (예: 조건 연산자 사용)
13683정성태7/18/20247651오류 유형: 917. ClrMD - Linux 환경의 .NET 5 덤프 분석 시 hang 현상
13682정성태7/18/20247869닷넷: 2278. WPF - 스레드에 종속되는 DependencyObject파일 다운로드1
13681정성태7/17/20247471닷넷: 2277. C# 13 - (2) 메서드 그룹의 자연 타입 개선 (메서드 추론 개선)파일 다운로드1
13680정성태7/16/20247857닷넷: 2276. C# - Method Group, Natural Type, function_type파일 다운로드1
13679정성태7/16/20246935Linux: 76. Linux - C++ (getaddrinfo 등을 담고 있는) libnss 정적 링크
13678정성태7/15/20247065VS.NET IDE: 191. Visual Studio 2022 - .NET 5 프로젝트를 Docker Support로 실행했을 때 오류
13677정성태7/15/20247156오류 유형: 916. MSBuild - CheckEolTargetFramework (warning NETSDK1138)
13676정성태7/14/20247328Linux: 75. gdb에서 glibc의 함수에 Breakpoint 걸기
13675정성태7/13/20249122C/C++: 166. C/C++ - DLL에서 template 함수를 export하는 방법 [1]파일 다운로드1
13674정성태7/13/20248003오류 유형: 915. Unhandled Exception: Microsoft.Diagnostics.NETCore.Client.ServerNotAvailableException: Unable to connect to Process
13673정성태7/11/20248444닷넷: 2275. C# 13 - (1) 신규 이스케이프 시퀀스 '\e'파일 다운로드1
13672정성태7/10/20247153닷넷: 2274. IIS - (프로세스 종료 없는) AppDomain Recycle
13671정성태7/10/20247263오류 유형: 914. Package ca-certificates is not installed.
13669정성태7/9/20247381오류 유형: 913. C# - AOT StaticExecutable 정적 링킹 시 빌드 오류
13668정성태7/8/20247399개발 환경 구성: 716. Hyper-V - Ubuntu 22.04 Generation 2 유형의 VM 설치
13667정성태7/7/20246622닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...