성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리</h1> <p> 아래와 같은 질문이 있었군요. ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 작업이 종료된 Thread의 객체는 가비지 컬렉터가 삭제 시키나요?? ; <a target='tab' href='https://forum.dotnetdev.kr/t/thread/8289'>https://forum.dotnetdev.kr/t/thread/8289</a> </pre> <br /> 위의 상황을 설명하는 코드를 우선, native 자원이 없는 개체를 만들어 유사하게 만들어 보면 아래와 같습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > namespace ConsoleApp1; internal class Program { static void Main(string[] args) { <span style='color: blue; font-weight: bold'>Program instance;</span> while (true) { <span style='color: blue; font-weight: bold'>Program p</span> = new Program(); <span style='color: blue; font-weight: bold'>instance = p;</span> Thread.Sleep(1000); } } } </pre> <br /> 위와 같은 경우에, Program 개체는 끊임없이 생성되면서 지역 변수인 instance에 대입이 되고 있습니다. 그렇다면, 마지막 개체를 제외하고 그 이전의 개체들이 GC가 구동되면 살아 있게 될까요?<br /> <br /> 사실, 원칙만 알고 있다면 어렵게 생각할 것이 없는 문제입니다. 여기서 그 원칙이란 바로 "해당 개체를 참조하고 있는 root 개체"가 있느냐는 것입니다.<br /> <br /> 루프를 한 번 돌았을 때, "Object#1"은 instance 지역 변수가 root 개체로 참조를 하고 있기 때문에 당연히 GC가 될 수 없습니다. 반면, 그 이후에 "Object#2"가 생성돼 instance 지역 변수에 할당되면 이전의 "Object#1"은 지역 변수에서 더 이상 가리키고 있지 않기 때문에 root 참조 개체가 없는 상태로 바뀝니다.<br /> <br /> 결국, 가장 마지막의 개체만 빼고는 이전에 생성한 모든 개체들이 GC 대상이 돼 해제가 됩니다. 어렵지 않죠? ^^<br /> <br /> <hr style='width: 50%' /><br /> <br /> 자, 그런데 Thread는 왠지 뭔가 복잡해 보이는 타입으로 느껴집니다. 왜냐하면 운영체제의 스레드 자원과 엮여 있기 때문입니다. 하지만, 여기서도 원칙은 같습니다. GC는 그저 "해당 개체를 참조하고 있는 root 개체"가 없으면 무조건 해제한다는 것입니다.<br /> <br /> 그런 관점에서 Thread를 간단하게 재현해 보면 Native 자원을 하나 품고 있는 타입으로 생각해 볼 수 있습니다. 유사 코드로는 이렇게 작성할 수 있는데요,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System.Runtime.InteropServices; namespace ConsoleApp3; internal class Program { static void Main(string[] args) { ThreadLike instance; while (true) { ThreadLike p = new ThreadLike(); instance = p; Thread.Sleep(1000); } } } class ThreadLike { IntPtr _ptr; public ThreadLike() { _ptr = Marshal.AllocCoTaskMem(1024); // 1KB 비관리 메모리 할당 } } </pre> <br /> 자, 그럼 위와 같은 상황에서 GC는 ThreadLike 인스턴스를 (마지막 개체를 제외하고) 정리하지 못할까요?<br /> <br /> 당연히, 정리를 합니다. 하지만, 해제 단계에서 Native 자원까지는 정리하지 않는다는 점이 중요합니다. Thread 역시 마찬가지입니다. 닷넷 세계에서 생성한 Thread 인스턴스는 엄밀히 Native 세계의 스레드 종료 여부와 무관하게 정리될 수 있습니다.<br /> <br /> 진짜로 그런지 아래와 같은 코드로 테스트를 해보면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > namespace ConsoleApp1; internal class Program { static void Main(string[] args) { CreateThread(); Console.ReadLine(); } static WeakReference _wr; // GC 여부의 확인을 돕기 위해 약한 참조 변수를 하나 두고, private static void CreateThread() { Thread t = new Thread(new ThreadStart(DoWork)); t.Start(); _wr = new WeakReference(t); // 생성한 스레드의 약한 참조를 유지 } private static void DoWork() { while (true) { Console.WriteLine(_wr.Target); // 1초 단위로 GC를 수행하면서 스레드 개체가 GC 되었는지 확인 GC.Collect(); Thread.Sleep(1000); } } } </pre> <br /> 화면에는 WeakReference로 걸어두고 있는 Target이 끝까지 살아 있는 것을 볼 수 있습니다.<br /> <br /> 아니, "스레드 종료 여부"와 상관없이 GC가 수행될 수 있다면서요? 맞습니다. 원래는 t 인스턴스는 (스레드가 실행 중이더라도) GC가 되어야 합니다. 그런데 왜? GC가 안 되는 것일까요?<br /> <br /> 제가 뭐라고 그랬죠? ^^ "해당 개체를 참조하고 있는 root 개체"가 있으면 GC 정리가 안 된다고 했습니다. 즉, 위의 Thread t 인스턴스는 어딘가에서 참조를 하고 있는 것입니다. <br /> <br /> <hr style='width: 50%' /><br /> <br /> 이쯤에서 분석을 위해 windbg의 힘을 빌려보겠습니다. ^^<br /> <br /> 위의 응용 프로그램에 대해 windbg로 Thread 인스턴스를 heap에서 뒤져보면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 0:007> <span style='color: blue; font-weight: bold'>!name2ee System.Private.CoreLib.dll!System.Threading.Thread</span> Module: 00007ffca9f74000 Assembly: System.Private.CoreLib.dll Token: 00000000020002D3 MethodTable: 00007ffcaa1b4330 EEClass: 00007ffcaa10af80 Name: System.Threading.Thread 0:007> <span style='color: blue; font-weight: bold'>!dumpheap -mt 00007ffcaa1b4330</span> Address MT Size 01b727809f08 7ffcaa1b4330 72 01b72780a040 7ffcaa1b4330 72 </pre> <br /> 2개의 인스턴스가 나오는데, 그중 하나에 대해 root 개체를 살펴보면 이렇게 나옵니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 0:007> <span style='color: blue; font-weight: bold'>!gcroot 01b727809f08</span> HandleTable: 000001b724d513a8 <span style='color: blue; font-weight: bold'>(strong handle)</span> -> 01b727809f08 System.Threading.Thread Found 1 unique roots. </pre> <br /> 보는 바와 같이, "strong handle" 유형의 자원에서 Thread 인스턴스에 대한 참조를 유지하고 있습니다. 실제로 GC Handle 영역을 뒤져보면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 0:007> <span style='color: blue; font-weight: bold'>!gchandles</span> Handle Type Object Size Data Type ...[생략]... 000001B724D513A0 Strong 000001b727809fb0 144 System.Object[] <span style='color: blue; font-weight: bold'>000001B724D513A8 Strong 000001b727809f08 72 System.Threading.Thread</span> 000001B724D513B0 Strong 000001b725002430 8184 System.Object[] 000001B724D513C0 Strong 000001b725002018 1048 System.Object[] 000001B724D513C8 Strong 000001b727800180 128 System.ExecutionEngineException 000001B724D513D0 Strong 000001b727800100 128 System.StackOverflowException 000001B724D513D8 Strong 000001b727800080 128 System.OutOfMemoryException 000001B724D513E0 Strong 000001b727800020 96 System.Int32[] 000001B724D513E8 Strong 000001b725000020 8184 System.Object[] 000001B724D513F8 Strong 000001b72780a040 72 System.Threading.Thread 000001B724D515F8 Pinned 000001b727800200 24 System.Object Statistics: MT Count TotalSize Class Name 00007ffca9f793b8 1 24 System.Object 00007ffcaa11bf38 1 96 System.Int32[] 00007ffcaa1b32b8 1 128 System.ExecutionEngineException 00007ffcaa1b31b8 1 128 System.StackOverflowException 00007ffcaa1b30b8 1 128 System.OutOfMemoryException 00007ffcaa229410 1 184 System.Diagnostics.Tracing.NativeRuntimeEventSource 00007ffcaa223550 4 256 Interop+Advapi32+EtwEnableCallback 00007ffcaa1b4330 5 360 System.Threading.Thread 00007ffcaa221500 1 384 System.Diagnostics.Tracing.RuntimeEventSource 00007ffcaa09aa68 4 17560 System.Object[] Total 20 objects Handles: Strong Handles: 10 Pinned Handles: 1 Weak Long Handles: 4 Weak Short Handles: 5 </pre> <br /> Strong 타입의 Handle 값 하나가 스레드 자원에 대한 GC Heap 주솟값을 가리키고 있는 것을 볼 수 있습니다. 바로 저 루트 개체가 GC를 막고 있는 건데요, (확인해 본 것은 아니지만 아마도) 스레드 종료 시까지 저 값을 유지시키는 듯하기 때문에 결국 네이티브 스레드가 종료하지 않는 한 그와 대응하는 관리 개체인 Thread 인스턴스도 GC가 안 되는 것입니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 참고로, 지난 글에서 "strong handle"로 등록되는 자원 중의 한 유형이 "ThreadStatic" 인스턴스라고 설명한 적이 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Windbg - ThreadStatic 필드 값을 조사하는 방법 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/13414'>https://www.sysnet.pe.kr/2/0/13414</a> </pre> <br /> 재미있게도 Thread 타입의 소스 코드를 보면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // 닷넷 버전에 따라 다를 수 있습니다. // <a target='tab' href='https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs,3980e012bae82e96'>https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs,3980e012bae82e96</a> namespace System.Threading { public sealed partial class Thread : CriticalFinalizerObject { private static AsyncLocal<IPrincipal?>? s_asyncLocalPrincipal; <span style='color: blue; font-weight: bold'>[ThreadStatic]</span> <span style='color: blue; font-weight: bold'>private static Thread? t_currentThread;</span> // ...[생략]... } } </pre> <br /> 저렇게 ThreadStatic 유형으로 Thread? t_currentThread 변수가 있기는 한데요, 이것과 실제 Thread 타입을 가리키는 GC Handle과는 아무런 관련이 없습니다. t_currentThread 필드는 Thread.CurrentThread에 대한 cache 용도로만 사용되는데,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > private static Thread InitializeCurrentThread() => t_currentThread = GetCurrentThreadNative(); public static Thread CurrentThread { [Intrinsic] get { return t_currentThread ?? InitializeCurrentThread(); } } </pre> <br /> 확인을 위해 다음과 같은 소스 코드로 확인해 보면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Thread t = new Thread((arg) => { var threadField = typeof(Thread).GetField("t_currentThread", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); Console.WriteLine($"{threadField.GetValue(null) ?? "(null)"}"); // "(null)" 출력 <span style='color: blue; font-weight: bold'>Thread.CurrentThread</span>.Name = $"Thread {number}"; Console.WriteLine($"{threadField.GetValue(null) ?? "(null)"}"); // "System.Threading.Thread" 출력 Console.ReadLine(); }); </pre> <br /> 결과에서 보듯이, CurrentThread 필드를 접근해야만 값이 채워지는 것을 볼 수 있습니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 암튼, 닷넷 런타임에서는 Thread 자원에 대해서는 (다른 여타 native 자원과는 달리) 특별한 루트 유지를 하고 있다는 점! (심지어 커널에서도 <a target='tab' href='https://devblogs.microsoft.com/oldnewthing/20231031-00/?p=108944'>스레드 자원의 해제</a>는 특별합니다.)<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1337
(왼쪽의 숫자를 입력해야 합니다.)