성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
[정성태] Modules 창(Ctrl+Shift+U)을 띄워서, 해당 Op...
[정성태] 만드실 수 있습니다. 단지, Unity 엔진 내의 스크립트와 W...
[공진영] 안녕하세요 좋은글 감사합니다. 현재 제가 wpf로 관제 모...
글쓰기
제목
이름
암호
전자우편
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'>.NET Thread 상태가 Cooperative일 때 GC hang 현상 재현 방법</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;' > C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상 ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/11473'>http://www.sysnet.pe.kr/2/0/11473</a> </pre> <br /> <div style='BACKGROUND-COLOR: #ccffcc; padding: 10px 10px 5px 10px; MARGIN: 0px 10px 10px 10px; FONT-FAMILY: Malgun Gothic, Consolas, Verdana; COLOR: #005555'> 각각의 스레드는 GC 작업을 해도 괜찮은 지에 대한 상태를 Preemptive와 Cooperative로 나눠 구분하는데, 전자의 경우가 안전한 것이고 후자의 상태에 있는 스레드가 있다면 GC 스레드는 GC 작업을 수행하지 않고 대상 스레드가 Cooperative에서 Preemptive 상태로 바뀔 때까지 대기하게 됩니다.<br /> </div><br /> <br /> 라고 언급한 적이 있습니다. (이것을 다르게 말하면, GC는 cooperative 스레드를 모두 중지(suspend)시키고 그 지점이 GC 작업에 안전한 곳인지 확인합니다. 만약 안전하지 않으면 해당 스레드만 resume 시켜 실행 후 안전한 지점에 머무를 때까지 대기합니다.) 제가 출처를 안 남겼었군요. ^^ 위의 내용은 다음의 글에 있었습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > MANAGED DEBUGGING with WINDBG. Managed Heap. Part 1 ; <a target='tab' href='https://learn.microsoft.com/ko-kr/archive/blogs/alejacma/managed-debugging-with-windbg-managed-heap-part-1'>https://learn.microsoft.com/ko-kr/archive/blogs/alejacma/managed-debugging-with-windbg-managed-heap-part-1</a> </pre> <br /> <div style='BACKGROUND-COLOR: #ccffcc; padding: 10px 10px 5px 10px; MARGIN: 0px 10px 10px 10px; FONT-FAMILY: Malgun Gothic, Consolas, Verdana; COLOR: #005555'> Preemptive GC indicates what GC mode the thread is in: "enabled" in the table means the thread is in preemptive mode where GC could preempt this thread at any time; <span style='color: blue; font-weight: bold'>"disabled" means the thread is in cooperative mode where GC has to wait the thread to give up its current work</span> (the work is related to GC objects so it can't allow GC to move the objects around). When the thread is executing managed code (the current IP is in managed code), it is always in cooperative mode; when the thread is in Execution Engine (unmanaged code), EE code could choose to stay in either mode and could switch mode at any time; when a thread is outside of CLR (i.e. calling into native code using interop), it is always in preemptive mode. </div><br /> <br /> 위에서 보면 스레드가 실행하고 있는 코드 유형에 따라 다음과 같이 3가지 정도로 나눌 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 1. 관리 코드를 실행 중일 때 (즉, IP 레지스터가 관리 코드 영역의 주소를 담고 있을 때) 2. 비관리 코드를 실행 중일 때, 2.1 CLR의 Execution Engine 내의 비관리 코드를 실행 중일 떄 2.2 그 이외의 비관리 코드를 실행 중일 때 </pre> <br /> 이중에서 Cooperative 모드인 경우는 1번과 2.1번에 해당합니다. 그리고 그중에서도 2.1번의 경우에는 preemptive/cooperative 모드 중 하나일 수 있으면서 언제든지 모드 전환을 할 수 있다고 하며, 1번의 경우에는 항상 cooperative 상태라고 합니다.<br /> <br /> 오호~~~ 그렇다면 cooperative 모드를 쉽게 재현할 수 있겠는데, 가령 다음과 같이 예제 코드를 작성하면 됩니다.<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 void threadFunc() { Console.WriteLine("threadFunc TID: " + AppDomain.GetCurrentThreadId()); long sum = 0; <span style='color: blue; font-weight: bold'>for (long i = 0; i < long.MaxValue; i ++) { sum += i; }</span> Console.WriteLine("SUM: " + sum); } </pre> <br /> 저 코드의 for-loop 수행 중에는 cooperative 상태라고 떠야 합니다. 실제로 위의 코드를 포함한 콘솔 프로그램을 실행하고 windbg로 연결해 다음과 같이 스레드 상태를 확인할 수 있습니다.<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='http://www.sysnet.pe.kr/2/0/943'>.loadby sos clr</a> 0:007> <span style='color: blue; font-weight: bold'>!threads</span> ThreadCount: 3 UnstartedThread: 0 BackgroundThread: 2 PendingThread: 0 DeadThread: 0 Hosted Runtime: no Lock ID OSID ThreadOBJ State GC Mode GC Alloc Context Domain Count Apt Exception 0 1 8364 00000236d48851d0 2a020 Preemptive 0000000000000000:0000000000000000 00000236d4869720 1 MTA 6 2 82d8 00000236d48cf990 2b220 Preemptive 0000000000000000:0000000000000000 00000236d4869720 0 MTA (Finalizer) 7 3 5810 00000236d4909f90 2b220 <span style='color: blue; font-weight: bold'>Cooperative</span> 0000000000000000:0000000000000000 00000236d4869720 0 MTA </pre> <br /> 저렇게 코딩했다면 언제나 1개는 Cooperative 모드의 스레드를 확인할 수 있습니다. 그나저나, Cooperative 모드 상태에서는 GC 측에서 해당 스레드가 안전한 영역으로 이동할 때까지 대기해야 한다고 했습니다. 그런데 실제로 해 보면 GC가 잘 호출이 됩니다. 어찌 보면 당연한 건데, 일례로 무한 루프에 빠진 관리 코드가 있다면 해당 프로세스는 영원히 GC가 안 된다는 의미가 되기 때문입니다.<br /> <br /> 그럼, 문서가 잘못된 걸까요? 그건 아닌 것 같고 Cooperative 모드이면서 아래의 조건에 해당하는 작업을 하는 동안이라는 단서가 붙습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > (the work is related to GC objects so it can't allow GC to move the objects around) </pre> <br /> 이를 재현하기 위해서는 열심히 GC 힙의 객체를 건드리는 코드를 넣어 보면 됩니다.<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 void allocThreadFunc() { Random rand = new Random(Environment.TickCount); while (true) { int count = rand.Next(500, 1000); List<int> list = new List<int>(); for (int i = 0; i < count; i ++) { list.Add(i); } } } </pre> <br /> 위의 코드를 실행하고 역시 windbg로 연결해 보면 스레드 상태를 다음과 같이 확인할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Lock ID OSID ThreadOBJ State GC Mode GC Alloc Context Domain Count Apt Exception 0 1 8364 00000236d48851d0 2a020 Preemptive 0000000000000000:0000000000000000 00000236d4869720 1 MTA 6 2 82d8 00000236d48cf990 2b220 Preemptive 0000000000000000:0000000000000000 00000236d4869720 0 MTA (Finalizer) 7 3 5810 00000236d4909f90 2b220 Cooperative 0000000000000000:0000000000000000 00000236d4869720 0 MTA 8 4 1c94 00000236d490b060 2b220 Cooperative <span style='color: blue; font-weight: bold'>00000236D67FC9B8:00000236D67FE1B0</span> 00000236d4869720 0 MTA </pre> <br /> 혹시, 그럼 저렇게 "GC Alloc Context"에 값이 있는 Cooperative의 스레드가 있을 때는 GC가 구동을 못하는 것 아닐까요?<br /> <br /> 테스트는 약간 조잡하지만 간단하게 해볼 수 있습니다. 위의 프로그램을 실행하고 Process Explorer를 이용해 allocThreadFunc을 호출하는 스레드를 일시 중지(Suspend)시키는 것입니다. 그다음 windbg의 !threads 명령어로 확인했을 때 GC Alloc Context의 값이 있어야 합니다. 만약, 없다면 다시 ^^ Process Explorer의 스레드 창에서 allocThreadFunc을 재개하고 다시 중지시키는 것입니다.<br /> <br /> 높은 확률로 GC Alloc Context에 값이 나온 상태의 스레드 중지를 할 수 있을 것입니다. 그런 상태에서 GC.Collect를 호출해 보면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > { Console.WriteLine("before: GC.Collect"); GCCount(); <span style='color: blue; font-weight: bold'>GC.Collect(2);</span> GCCount(); Console.WriteLine("after: GC.Collect"); Console.ReadLine(); } </pre> <br /> 와~~~ 정말 GC.Collect 메서드가 끝나질 않습니다. 이렇게 blocking 된 상태의 !threads 명령어를 보면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 0:008> !threads ThreadCount: 4 UnstartedThread: 0 BackgroundThread: 3 PendingThread: 0 DeadThread: 0 Hosted Runtime: no Lock ID OSID ThreadOBJ State GC Mode GC Alloc Context Domain Count Apt Exception 0 1 2bb0 000001b5bd072600 2a020 Preemptive <span style='color: blue; font-weight: bold'>000001B5BEF64860:000001B5BEF667B0</span> 000001b5bd0482f0 1 MTA <span style='color: blue; font-weight: bold'>(GC) </span> 3 2 64d0 000001b5bd09d5c0 2b220 Preemptive 0000000000000000:0000000000000000 000001b5bd0482f0 0 MTA (Finalizer) 4 3 51a0 000001b5bd0c6700 2b220 Preemptive 0000000000000000:0000000000000000 000001b5bd0482f0 0 MTA 5 4 f44 000001b5bd0d5bb0 2b2a2 Cooperative 000001B5BEF62DB8:000001B5BEF647B0 000001b5bd0482f0 0 MTA </pre> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 2bb0 == GC.Collect 수행 스레드 f44 == allocThreadFunc 실행 중 suspend된 스레드 </pre> <br /> GC.Collect를 호출한 스레드에도 "GC Alloc Context" 값이 있고 마지막에 GC 수행 중임을 알리는 "(GC)" 문자열도 보입니다. 이어서 GC.Collect를 수행한 스레드의 콜 스택을 보면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 0:000> k # Child-SP RetAddr Call Site 00 0000002d`69afe618 00007ffa`18db9252 ntdll!<span style='color: blue; font-weight: bold'>NtWaitForSingleObject</span>+0x14 01 0000002d`69afe620 00007ffa`059d2c77 KERNELBASE!WaitForSingleObjectEx+0xa2 02 0000002d`69afe6c0 00007ffa`059d2c2f clr!LogHelp_NoGuiOnAssert+0x23b87 03 0000002d`69afe700 00007ffa`059d2bb0 clr!LogHelp_NoGuiOnAssert+0x23b3f 04 0000002d`69afe760 00007ffa`05a08854 clr!LogHelp_NoGuiOnAssert+0x23ac0 05 0000002d`69afe7f0 00007ffa`05a06704 clr!LogHelp_NoGuiOnAssert+0x59764 06 0000002d`69afe8e0 00007ffa`05b4bbb3 clr!LogHelp_NoGuiOnAssert+0x57614 07 0000002d`69afe9e0 00007ffa`05b06e7d clr!ClrCreateManagedInstance+0x4a763 08 0000002d`69afea40 00007ffa`05af3efa clr!ClrCreateManagedInstance+0x5a2d 09 0000002d`69afea90 00007ffa`02dfd1fa clr!PreBindAssemblyEx+0x31ca 0a 0000002d`69afeb20 00007ffa`02dfd065 mscorlib_ni!System.<span style='color: blue; font-weight: bold'>GC.Collect</span>(Int32, System.GCCollectionMode, Boolean, Boolean)$##6000E92+0xaa ...[생략]... 16 0000002d`69affa30 00007ffa`0f0aa4cc mscoreei!CorExeMain+0x112 17 0000002d`69affa90 00007ffa`1ab33034 MSCOREE!CorExeMain_Exported+0x6c 18 0000002d`69affac0 00007ffa`1c491431 KERNEL32!BaseThreadInitThunk+0x14 19 0000002d`69affaf0 00000000`00000000 ntdll!RtlUserThreadStart+0x21 </pre> <br /> GC.Collect 내부 호출 과정 중에 NtWaitForSingleObject에 걸려 있습니다. 만약 이런 상태의 hang이 걸린 경우 덤프를 뜨고 "<a target='tab' href='http://www.sysnet.pe.kr/2/0/1026'>DebugDiag Analysis</a>"를 돌려 보면 다음과 같은 메시지를 확인할 수 있습니다.<br /> <br /> <div style='BACKGROUND-COLOR: #ccffcc; padding: 10px 10px 5px 10px; MARGIN: 0px 10px 10px 10px; FONT-FAMILY: Malgun Gothic, Consolas, Verdana; COLOR: #005555'> The following threads in ConsoleApp1.dmp are waiting for .net garbage collection to finish. <span style='color: blue; font-weight: bold'>Thread 0 triggered the garbage collection.</span> The gargage collector thread <span style='color: blue; font-weight: bold'>wont start doing its work till the time the threads which have pre-emptive GC disabled have finished executing. The following threads have pre-emptive GC disabled 5,</span> </div><br /> <br /> 위에서 "pre-emptive GC disabled" 상태가 바로 Cooperative 모드입니다. 즉, 디버거 스레드 id 5번에 해당하는 스레드가 현재 Cooperative 모드로부터 풀릴 때까지 대기하고 있다는 것입니다. 재미있는 건, 해당 스레드의 호출 스택을 DebugDiag가 더 잘 보여준다는 것입니다. 실제로 다음과 같은 호출 스택을 보여주는데,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > ntdll!NtWaitForSingleObject+14 KERNELBASE!WaitForSingleObjectEx+a2 clr!CLREventWaitHelper2+3c clr!CLREventWaitHelper+1f <span style='color: blue; font-weight: bold'>clr!CLREventBase::WaitEx+7c clr!ThreadSuspend::SuspendRuntime+32c clr!ThreadSuspend::SuspendEE+128</span> clr!WKS::GCHeap::GarbageCollectGeneration+b7 clr!WKS::GCHeap::GarbageCollect+8d clr!GCInterface::Collect+6a mscorlib_ni!System.GC.Collect(Int32, System.GCCollectionMode, Boolean, Boolean)+aa [[InlinedCallFrame] (System.GC._Collect)] System.GC._Collect(Int32, Int32) mscorlib_ni!System.GC.Collect(Int32)+15 ConsoleApp1.Program.Main(System.String[])+173 ...[생략]... ntdll!RtlUserThreadStart+21 </pre> <br /> GC를 수행하기 위해 다른 스레드들이 안전한 지점에 이를 때까지 대기하고 있는 것을 유추해 볼 수 있습니다. 또한, 순수 닷넷 코드만을 실행시키던 threadFunc은 같은 시기에 다음과 같이 GC 작업이 완료되기를 기다리면서 중지 상태로 빠집니다. (즉, GC 수행 준비 기간부터 이미 중지 상태로 빠지는 것입니다.)<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > ntdll!NtWaitForSingleObject+14 KERNELBASE!WaitForSingleObjectEx+a2 clr!CLREventWaitHelper2+3c clr!CLREventWaitHelper+1f clr!CLREventBase::WaitEx+7c clr!WKS::GCHeap::WaitUntilGCComplete+2b clr!Thread::RareDisablePreemptiveGC+180 clr!Thread::RedirectedHandledJITCase+1bf [[RedirectedThreadFrame]] clr!RedirectedHandledJITCaseForGCThreadControl_Stub+26 ConsoleApp1.Program.threadFunc()+c6 ...[생략]... ntdll!RtlUserThreadStart+21 </pre> <br /> threadFunc의 저런 상태에 대해 비록 Full Framework은 아니지만 아래의 글에 있는 내용을 참고할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > NETCF: GC and thread blocking ; <a target='tab' href='https://learn.microsoft.com/ko-kr/archive/blogs/abhinaba/netcf-gc-and-thread-blocking'>https://learn.microsoft.com/ko-kr/archive/blogs/abhinaba/netcf-gc-and-thread-blocking</a> </pre> <br /> <div style='BACKGROUND-COLOR: #ccffcc; padding: 10px 10px 5px 10px; MARGIN: 0px 10px 10px 10px; FONT-FAMILY: Malgun Gothic, Consolas, Verdana; COLOR: #005555'> Before actually running GC the CLR tries to go into a “safe point”. <span style='color: blue; font-weight: bold'>Each thread has a suspend event associated with it and this event is checked by each thread regularly.</span> Before starting GC the CLR enumerates all managed threads and in each of them sets this event. In the next point when the thread checks and finds this event set, it blocks waiting for the event to get reset (which happens when GC is complete). </div><br /> <br /> 이 정도면, preemptive/cooperative 모드에 대한 미스터리가 어느 정도 풀린 것 같습니다. ^^<br /> <br /> (<a target='tab' href='http://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1324&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1827
(왼쪽의 숫자를 입력해야 합니다.)