Microsoft MVP성태의 닷넷 이야기
.NET Framework: 734. C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상 [링크 복사], [링크+제목 복사],
조회: 24695
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 4개 있습니다.)
.NET Framework: 734. C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상
; https://www.sysnet.pe.kr/2/0/11473

디버깅 기술: 113. windbg - Thread.Suspend 호출 시 응용 프로그램 hang 현상에 대한 덤프 분석
; https://www.sysnet.pe.kr/2/0/11475

.NET Framework: 863. C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상을 해결하기 위한 시도
; https://www.sysnet.pe.kr/2/0/12028

.NET Framework: 1056. C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상 (2)
; https://www.sysnet.pe.kr/2/0/12626




C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상

닷넷에서, 다른 스레드의 콜 스택을 얻는 여러 가지 방법이 있지만,

.NET에서의 스레드 콜 스택 덤프
; https://www.sysnet.pe.kr/2/0/802

"Stack Walking" in the .NET Runtime
; https://mattwarren.org/2019/01/21/Stackwalking-in-the-.NET-Runtime/

그중에서 (제 경험으로는) 가장 안정적인 것은 System.Diagnostics.StackTrace를 이용하는 방법이었습니다. 그런데, 이것을 사용하기 위해서는 대상 스레드를 반드시 Suspend 시켜야 합니다. 그리고 Suspend 메서드의 경우,

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

주의 사항으로 다음과 같은 문구가 있습니다.

Do not use the Suspend and Resume methods to synchronize the activities of threads. You have no way of knowing what code a thread is executing when you suspend it. If you suspend a thread while it holds locks during a security permission evaluation, other threads in the AppDomain might be blocked. If you suspend a thread while it is executing a class constructor, other threads in the AppDomain that attempt to use that class are blocked. Deadlocks can occur very easily.


hang 현상은 다음과 같은 코드로 쉽게 재현이 가능합니다.

using System;
using System.Collections.Generic;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        List<Thread> _threads = new List<Thread>();

        static void Main(string[] args)
        {
            Program pg = new Program();
            pg.Start();
            Console.ReadLine();
        }

        int _count = 0;
        int _gcCount = 0;

        private void Start()
        {
            for (int i = 0; i < 4; i++)
            {
                Thread t = new Thread(threadFunc);
                _threads.Add(t);
                t.IsBackground = true;
                t.Name = i.ToString();
                t.Start();
            }

            Thread.Sleep(5000);
            Random rd = new Random(Environment.TickCount);

            while (true)
            {
                _count++;
                int idx = rd.Next(0, _threads.Count - 1);
                Thread t = _threads[idx];

                {
                    GetCallStack(t);
                }

                _gcCount = GC.CollectionCount(2);

                if (_count % 100 == 0)
                {
                    Console.WriteLine(_count + ": " + _gcCount);
                }
            }
        }

        private static string GetCallStack(Thread t)
        {
            System.Diagnostics.StackTrace trace = null;
            t.Suspend();
            try
            {
                trace = new System.Diagnostics.StackTrace(t, false);
                return trace.ToString();
            }
            catch
            {
            }
            finally
            {
                try
                {
                    t.Resume();
                }
                catch { }
            }

            return "";
        }

        private static void threadFunc()
        {
            List<byte[]> _bufs = new List<byte[]>();

            while (true)
            {
                byte[] buf1 = new byte[4096 * 512];
                lock (_bufs)
                {
                    _bufs.Add(buf1);

                    if (_bufs.Count >= 2)
                    {
                        _bufs.Clear();
                    }
                }

                Thread.Sleep(10);
            }
        }
    }
}

/*

app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.1" />
    </startup>

    <runtime>
        <gcServer enabled="true"/>
    </runtime>
</configuration>

*/

실행해 보면, 무작위 시점에서 응용 프로그램이 멈추는 것을 확인할 수 있습니다.

이유는 간단합니다. 스레드 하나가 new로 관리 힙에 객체를 생성하다가 어느 순간 GC가 필요하다고 판단될 때가 있습니다. 하지만, GC를 수행하는 스레드는 GC 작업을 수행해도 안전한지에 대해 다른 스레드들의 상태를 확인합니다. 각각의 스레드는 GC 작업을 해도 괜찮은 지에 대한 상태를 Preemptive와 Cooperative로 나눠 구분하는데, 전자의 경우가 안전한 것이고 후자의 상태에 있는 스레드가 있다면 GC 스레드는 GC 작업을 수행하지 않고 대상 스레드를 멈춘(suspend) 후 안전 영역의 코드를 수행 중인지 다시 확인합니다. 만약 안전 영역이라면 GC 수행을 할 수 있고, 안전하지 않다면 안전 영역으로 나올 수 있도록 스레드를 resume 시킨 후 GC는 대기하게 됩니다. (Resume으로 다시 동작하게 된 스레드는 안전 영역으로 나오자마자 GC가 수행되도록 blocking됩니다.)

다시 정리해 보면, A 스레드가 GC를 수행해야 한다고 판단했고 다른 스레드의 상태를 체크하는 코드를 수행 중입니다. 그런데 바로 그 시점에 B 스레드가 A 스레드를 Suspend 시키고 A 스레드의 호출 스택을 가져오려고 합니다. 여기서 문제는, 호출 스택을 가져오려는 그 동작조차도 "new"로 인한 관리 힙을 사용하려고 시도하기 때문에 관리 힙이 GC를 위한 준비 상태이므로 GC 작업이 끝날 때까지 대기하게 됩니다. 결국 B 스레드는 A 스레드를 Resume하지 못하고 대기하므로 이 시점부터 응용 프로그램의 모든 스레드에서 "new"를 호출하기만 하면 대기 상태에 빠지게 됩니다. 한마디로, 응용 프로그램 레벨에서 hang 상태에 빠지는 것입니다.

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




이 사례에 비춰서 "If you suspend a thread while it holds locks during a security permission evaluation" 구문도 유추할 수 있습니다. 즉, 보안 권한에 대한 평가를 위해 내부적으로 CLR은 lock을 획득한다는 것이고, 그 상태의 스레드를 Suspend 시킨 측의 스레드가 Resume을 호출하기 전 역시 보안 권한에 대한 평가를 하는 코드를 호출하게 된다면... 으로 해석할 수 있습니다.




(2020-10-09 업데이트) 이런 문제를 방지하려면 GC 수행이 있을 것이라는 감지를 하면 될 텐데, 이게 또 쉽지 않습니다. ^^; 일례로 다음의 글에 보면,

Thread.Suspend Method
; https://mattwarren.org/2016/08/08/GC-Pauses-and-Safe-Points/

ETW를 이용해 GC의 실행 예측을 할 수 있지만,
  1. GCSuspendEE_V1
  2. GCSuspendEEEnd_V1 <- suspension is done
  3. GCStart_V1
  4. GCEnd_V1 <- actual GC is done
  5. GCRestartEEBegin_V1
  6. GCRestartEEEnd_V1 <- resumption is done.
아쉽게도 예전에 설명했듯이 ETW는 실시간이 아니므로,

ETW(Event Tracing for Windows)를 이용한 닷넷 프로그램의 내부 이벤트 활용
; https://www.sysnet.pe.kr/2/0/12244

C# - ETW 관련 Win32 API 사용 예제 코드 (4) CLR ETW Consumer
; https://www.sysnet.pe.kr/2/0/12300

스레드 제어 시 사용할 수 없습니다. 또 다른 방법으로, CLR Profiler 관련한 GC 이벤트를 받는 것인데 이것은 실시간은 만족하지만 이로 인한 부하가 심해져,

windbg 분석 사례 - 닷넷 프로파일러의 GC 콜백 부하
; https://www.sysnet.pe.kr/2/0/10897

역시 현실적인 수준에서 사용할 수 없습니다.
(혹시 좋은 방법이 있으신 분은 덧글 부탁드립니다. ^^)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/21/2023]

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

비밀번호

댓글 작성자
 




... 121  122  123  124  125  126  127  128  129  [130]  131  132  133  134  135  ...
NoWriterDateCnt.TitleFile(s)
1806정성태11/10/201425139.NET Framework: 477. SeCreateGlobalPrivilege 특권과 WCF NamedPipe
1805정성태11/5/201422004.NET Framework: 476. Visual Studio에서 Mono용 Profiler 개발 [3]파일 다운로드1
1804정성태11/5/201428262.NET Framework: 475. ETW(Event Tracing for Windows)를 C#에서 사용하는 방법 [9]파일 다운로드1
1803정성태11/4/201420358오류 유형: 261. Windows Server Backup 오류 - Error in backup of E:\$Extend\$RmMetadata\$TxfLog
1802정성태11/4/201422295오류 유형: 260. 이벤트 로그 - Windows Error Reporting / AEAPPINVW8
1801정성태11/4/201427613오류 유형: 259. 이벤트 로그 - Windows Error Reporting / IPX Assertion / KorIME.exe [1]
1800정성태11/4/201418280오류 유형: 258. 이벤트 로그 - Starting a SMART disk polling operation in Automatic mode.
1799정성태11/4/201423072오류 유형: 257. 이벤트 로그 - The WMI Performance Adapter service entered the stopped state.
1798정성태11/4/201431865오류 유형: 256. 이벤트 로그 - The WinHTTP Web Proxy Auto-Discovery Service service entered the stopped state. [1]
1797정성태11/4/201417588오류 유형: 255. 이벤트 로그 - The Adobe Flash Player Update Service service entered the stopped state.
1796정성태10/30/201424551개발 환경 구성: 249. Visual Studio 2013에서 Mono 컴파일하는 방법
1795정성태10/29/201427094개발 환경 구성: 248. Lync 2013 서버 설치 방법
1794정성태10/29/201422503개발 환경 구성: 247. "Microsoft Office 365 Enterprise E3" 서비스에 대한 간략 소개
1793정성태10/27/201423165.NET Framework: 474. C# - chromiumembedded 사용 - 두 번째 이야기 [2]파일 다운로드1
1792정성태10/27/201423287.NET Framework: 473. WebClient 객체에 쿠키(Cookie)를 사용하는 방법
1791정성태10/22/201423012VC++: 83. G++ - 템플릿 클래스의 iterator 코드 사용에서 발생하는 컴파일 오류 [5]
1790정성태10/22/201418539오류 유형: 254. NETLOGON Service is paused on [... AD Server...]
1789정성태10/22/201421215오류 유형: 253. 이벤트 로그 - The client-side extension could not remove user policy settings for '...'
1788정성태10/22/201423239VC++: 82. COM 프로그래밍에서 HRESULT 타입의 S_FALSE는 실패일까요? 성공일까요? [2]
1787정성태10/22/201431408오류 유형: 252. COM 개체 등록시 0x8002801C 오류가 발생한다면?
1786정성태10/22/201432739디버깅 기술: 65. 프로세스 비정상 종료 시 "Debug Diagnostic Tool"를 이용해 덤프를 남기는 방법 [3]파일 다운로드1
1785정성태10/22/201421945오류 유형: 251. 이벤트 로그 - Load control template file /_controltemplates/TaxonomyPicker.ascx failed [1]
1784정성태10/22/201430032.NET Framework: 472. C/C++과 C# 사이의 메모리 할당/해제 방법파일 다운로드1
1783정성태10/21/201423497VC++: 81. 프로그래밍에서 borrowing의 개념
1782정성태10/21/201420221오류 유형: 250. 이벤트 로그 - Application Server job failed for service instance Microsoft.Office.Server.Search.Administration.SearchServiceInstance
1781정성태10/21/201420687디버깅 기술: 64. new/delete의 짝이 맞는 경우에도 메모리 누수가 발생한다면?
... 121  122  123  124  125  126  127  128  129  [130]  131  132  133  134  135  ...