Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 5개 있습니다.)
.NET Framework: 2064. C# - Mutex와 Semaphore/SemaphoreSlim 차이점
; https://www.sysnet.pe.kr/2/0/13156

.NET Framework: 2065. C# - Mutex의 비동기 버전
; https://www.sysnet.pe.kr/2/0/13157

닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
; https://www.sysnet.pe.kr/2/0/13555

닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
; https://www.sysnet.pe.kr/2/0/13558

디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
; https://www.sysnet.pe.kr/2/0/13560




windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)

지난 글에서,

C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
; https://www.sysnet.pe.kr/2/0/13558

Mutex를 사용해 hang 현상이 발생한 경우 어떻게 잠금을 추적할 수 있는지 설명했는데요, 동일한 상황에서 (최댓값이 1인) SemaphoreSlim을 사용했을 때 디버깅이 어떻게 바뀌는지 살펴보겠습니다.




문제의 상황에서 덤프 파일을 뜨면, 가장 먼저 해야 할 것이 바로 "Debug Diagnostics"로 대강의 상황을 파악하는 것입니다.

실제 사례를 통해 Debug Diagnostics 도구가 생성한 닷넷 웹 응용 프로그램의 성능 장애 보고서 설명
; https://www.sysnet.pe.kr/2/0/12067

위의 방법에 따라 닷넷 프로세스를 분석했더니 6개의 스레드가 다음과 같은 호출 스택으로 나왔습니다.

[[GCFrame]]
[[HelperMethodFrame_1OBJ] (System.Threading.Monitor.ObjWait)] System.Threading.Monitor.ObjWait(Boolean, Int32, System.Object)
mscorlib_ni!System.Threading.SemaphoreSlim.WaitUntilCountOrTimeout(Int32, UInt32, System.Threading.CancellationToken)+8b
mscorlib_ni!System.Threading.SemaphoreSlim.Wait(Int32, System.Threading.CancellationToken)+151
SuperSimpleTcp.SimpleTcpServer.SendInternal(System.String, Int64, System.IO.Stream)+9e
SuperSimpleTcp.SimpleTcpServer.Send(System.String, Byte[])+a2
...[생략]...

문제는, ^^; 저 hang 상태를 유발한 Semaphore.Wait을 다른 스레드에서 찾을 수 없었다는 점입니다. 이후의 분석은 덤프 파일을 windbg로 열어 추적을 해야 하는데요, 위의 hang 상태에 빠진 스레드 6개 중 1개의 스레드로 문맥을 변경한 다음 "clrstack -a"로 SemaphoreSlim 인스턴스를 얻는 것으로 시작할 수 있습니다.

// DebugDiag로 분석한 스레드 중 1개를 선택, 이 글에서는 "59번 스레드"

0:000> ~59s
ntdll!NtWaitForMultipleObjects+0x14:
00007ffc`f53b59a4 c3              ret


// call stack과 그 스택으로부터 얻을 수 있는 SemaphoreSlim 인스턴스를 알아냄

0:059> !clrstack -a
OS Thread Id: 0x320c (59)
        Child SP               IP Call Site
000000d03d13e530 00007ffcf53b59a4 [GCFrame: 000000d03d13e530] 
000000d03d13e658 00007ffcf53b59a4 [HelperMethodFrame_1OBJ: 000000d03d13e658] System.Threading.Monitor.ObjWait(Boolean, Int32, System.Object)
000000d03d13e770 00007ffce43dac4b System.Threading.SemaphoreSlim.WaitUntilCountOrTimeout(Int32, UInt32, System.Threading.CancellationToken) [f:\dd\ndp\clr\src\BCL\system\threading\SemaphoreSlim.cs @ 469]
    PARAMETERS:
        this (<CLR reg>) = 0x0000021f6acc0ff8
        millisecondsTimeout (<CLR reg>) = 0x00000000ffffffff
        startTime (<CLR reg>) = 0x0000000000000000
        cancellationToken = <no data>

...[생략]...

그럼 해당 세마포어 인스턴스의 상태를 볼까요? ^^

0:059> !DumpObj /d 0000021f6acc0ff8
Name:        System.Threading.SemaphoreSlim
MethodTable: 00007ffce3506740
EEClass:     00007ffce374bc90
Size:        64(0x40) bytes
File:        C:\Windows\Microsoft.Net\assembly\GAC_64\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll
Fields:
              MT    Field   Offset                 Type VT     Attr            Value Name
00007ffce34885a0  4001a88       28         System.Int32  1 instance                0 m_currentCount
00007ffce34885a0  4001a89       2c         System.Int32  1 instance                1 m_maxCount
00007ffce34885a0  4001a8a       30         System.Int32  1 instance                6 m_waitCount
00007ffce3485dd8  4001a8b        8        System.Object  0 instance 0000000000000000 m_lockObj
00007ffce3504398  4001a8c       10 ....ManualResetEvent  0 instance 0000000000000000 m_waitHandle
00007ffce34d4f38  4001a8d       18 ...horeSlim+TaskNode  0 instance 0000000000000000 m_asyncHead
00007ffce34d4f38  4001a8e       20 ...horeSlim+TaskNode  0 instance 0000000000000000 m_asyncTail
00007ffce34a4ac0  4001a8f     1008 ...olean, mscorlib]]  0   shared           static s_trueTask
                                 >> Domain:Value  0000021d6a3b80e0:NotInit  0000021d6a4d3350:0000021d6a9a0058 <<
00007ffce34fa680  4001a91     1010 ...bject, mscorlib]]  0   shared           static s_cancellationTokenCanceledEventHandler
                                 >> Domain:Value  0000021d6a3b80e0:NotInit  0000021d6a4d3350:0000021d6a9a00a8 <<

m_maxCount를 통해 Semaphore가 "new SemaphoreSlim(1, 1)" 조건으로 생성된 것임을 짐작게 합니다. 또한, m_currentCount가 0이므로 이미 다른 곳에서 SemaphoreSlim.Wait을 호출해 한 번의 lock 조건을 소진한 상태이고, m_waitCount가 6인 것으로 봐서 해당 lock을 대기하고 있는 곳이 총 6개, 결국 DebugDiag가 분석한 6개의 스레드와 일치하는 결과를 보입니다.

따라서, 6개의 스레드가 동일한 SemaphoreSlim 1개에 걸려 hang 상태가 발생한 것입니다.

여기서 결정적인 문제점 하나가 나오는데요, m_lockObj가 null로 나오는 것에서 이미 저 SemaphoreSlim은 Dispose를 호출한 상태라는 점입니다. 바로 이 문제를 지난 글에서 다뤘던 것입니다.




문제의 덤프 파일을 발생시켰던 응용 프로그램은 call stack에도 나오듯이 SuperSimpleTcp를 사용한 경우였습니다.

C# - SuperSimpleTcp 사용 시 주의할 점
; https://www.sysnet.pe.kr/2/0/13532

SimpleTcpServer.cs 파일의 SendInternal에 보면 이런 코드가 나옵니다.

private void SendInternal(string ipPort, long contentLength, Stream stream)
{
    if (!_clients.TryGetValue(ipPort, out ClientMetadata client)) return;
    if (client == null) return;

    long bytesRemaining = contentLength;
    int bytesRead = 0;
    byte[] buffer = new byte[_settings.StreamBufferSize];

    try
    {
        client.SendLock.Wait();

        while (bytesRemaining > 0)
        {
            bytesRead = stream.Read(buffer, 0, buffer.Length);
            if (bytesRead > 0)
            {
                if (!_ssl) client.NetworkStream.Write(buffer, 0, bytesRead); 
                else client.SslStream.Write(buffer, 0, bytesRead); 

                bytesRemaining -= bytesRead;
                _statistics.SentBytes += bytesRead;
            }
        }

        if (!_ssl) client.NetworkStream.Flush();
        else client.SslStream.Flush();
        _events.HandleDataSent(this, new DataSentEventArgs(ipPort, contentLength));
    }
    finally
    {
        if (client != null) client.SendLock.Release();
    }
}

try/finally를 했기 때문에 쌍이 잘 맞습니다. 문제는, DisconnectClient 코드에서 나옵니다.

public void DisconnectClient(string ipPort)
{
    if (string.IsNullOrEmpty(ipPort)) throw new ArgumentNullException(nameof(ipPort));

    if (!_clients.TryGetValue(ipPort, out ClientMetadata client))
    {
        Logger?.Invoke($"{_header}unable to find client: {ipPort}");
    }
    else
    {
        if (!_clientsTimedout.ContainsKey(ipPort))
        {
            Logger?.Invoke($"{_header}kicking: {ipPort}");
            _clientsKicked.TryAdd(ipPort, DateTime.Now);
        }
    }

    if (client != null)
    {
        if (!client.TokenSource.IsCancellationRequested)
        {
            client.TokenSource.Cancel();
            Logger?.Invoke($"{_header}requesting disposal of: {ipPort}");
        }

        client.Dispose();
    }
}

ClientMetaData.cs에 정의된 client 인스턴스의 Dispose 메서드를 보면,

public void Dispose()
{ 
    if (TokenSource != null)
    {
        if (!TokenSource.IsCancellationRequested)
        {
            TokenSource.Cancel();
            TokenSource.Dispose();
        }
    }

    if (_sslStream != null)
    {
        _sslStream.Close(); 
    }

    if (_networkStream != null)
    {
        _networkStream.Close(); 
    }

    if (_tcpClient != null)
    {
        _tcpClient.Close();
        _tcpClient.Dispose(); 
    }

    SendLock.Dispose();
    ReceiveLock.Dispose();
}

단순히 SendLock.Dispose() 호출만을 하고 있습니다. 즉, (이전에 설명한 대로) 다른 SendInternal에서 Wait하고 있는 스레드들은 영원히 hang 상태에 빠져든 체로, 일종의 메모리 leak을 유발하게 되는 것입니다.




SuperSimpleTcp가 생성한 SemaphoreSlim은,

internal SemaphoreSlim SendLock = new SemaphoreSlim(1, 1);
internal SemaphoreSlim ReceiveLock = new SemaphoreSlim(1, 1);

lock(obj), Mutex 역할과 동일합니다. 하지만 그래도 SemaphoreSlim을 사용할 수밖에 없는 이유는 SendInternalAsync와 같은 비동기 함수를 제공하고 있기 때문인데요, 예전 글에 설명했던 대로,

C# - Mutex의 비동기 버전
; https://www.sysnet.pe.kr/2/0/13157

Mutex의 경우 비동기 구현을 하려면 결국 동기 방식의 스레드를 쓰거나 아니면 SemaphoreSlim으로 우회해야 합니다. (또한, lock, 즉 Monitor.Enter/Exit은 비동기 구문을 지원하지 않습니다.)

결국 비동기로 인해 SemaphoreSlim를 쓸 수밖에 없었던 것입니다. 만약, 비동기를 포기한다면 SendInternalAsync를 사용하지 않고 오직 SendInternal만 사용한다면 SemaphoreSlim 대신 lock을 사용하는 것이 문제를 그나마 쉽게 해결할 수 있습니다.

private void SendInternal(string ipPort, long contentLength, Stream stream)
{
    if (!_clients.TryGetValue(ipPort, out ClientMetadata client)) return;
    if (client == null) return;

    long bytesRemaining = contentLength;
    int bytesRead = 0;
    byte[] buffer = new byte[_settings.StreamBufferSize];

    bool lockTaken = false;
 
    try
    {
        // client.SendLock.Wait();
        Monitor.Enter(client.SendLock, ref lockTaken);

        while (bytesRemaining > 0)
        {
            bytesRead = stream.Read(buffer, 0, buffer.Length);
            if (bytesRead > 0)
            {
                if (!_ssl) client.NetworkStream.Write(buffer, 0, bytesRead); 
                else client.SslStream.Write(buffer, 0, bytesRead); 

                bytesRemaining -= bytesRead;
                _statistics.SentBytes += bytesRead;
            }
        }

        if (!_ssl) client.NetworkStream.Flush();
        else client.SslStream.Flush();
        _events.HandleDataSent(this, new DataSentEventArgs(ipPort, contentLength));
    }
    finally
    {
        if (lockTaken)
        {
            Monitor.Exit(client.SendLock);
        }

        // if (client != null) client.SendLock.Release();
    }
}

이와 함께, 혹시라도 SendInternalAsync를 사용할 수도 있으므로 비동기 관련 메서드들은 모두 private 처리하는 것이 좋습니다.




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







[최초 등록일: ]
[최종 수정일: 2/19/2024]

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

비밀번호

댓글 작성자
 




... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13156정성태11/7/20226805.NET Framework: 2064. C# - Mutex와 Semaphore/SemaphoreSlim 차이점파일 다운로드1
13155정성태11/4/20226305디버깅 기술: 183. TCP 동시 접속 (연결이 아닌) 시도를 1개로 제한한 서버
13154정성태11/3/20225779.NET Framework: 2063. .NET 5+부터 지원되는 GC.GetGCMemoryInfo파일 다운로드1
13153정성태11/2/20227070.NET Framework: 2062. C# - 코드로 재현하는 소켓 상태(SYN_SENT, SYN_RECV)
13152정성태11/1/20225687.NET Framework: 2061. ASP.NET Core - DI로 추가한 클래스의 초기화 방법 [1]
13151정성태10/31/20225790C/C++: 161. Windows 11 환경에서 raw socket 테스트하는 방법파일 다운로드1
13150정성태10/30/20225854C/C++: 160. Visual Studio 2022로 빌드한 C++ 프로그램을 위한 다른 PC에서 실행하는 방법
13149정성태10/27/20225769오류 유형: 825. C# - CLR ETW 이벤트 수신이 GCHeapStats_V1/V2에 대해 안 되는 문제파일 다운로드1
13148정성태10/26/20225781오류 유형: 824. msbuild 에러 - error NETSDK1005: Assets file '...\project.assets.json' doesn't have a target for 'net5.0'. Ensure that restore has run and that you have included 'net5.0' in the TargetFramew
13147정성태10/25/20224870오류 유형: 823. Visual Studio 2022 - Unable to attach to CoreCLR. The debugger's protocol is incompatible with the debuggee.
13146정성태10/24/20225710.NET Framework: 2060. C# - Java의 Xmx와 유사한 힙 메모리 최댓값 제어 옵션 HeapHardLimit
13145정성태10/21/20225996오류 유형: 822. db2 - Password validation for user db2inst1 failed with rc = -2146500508
13144정성태10/20/20225809.NET Framework: 2059. ClrMD를 이용해 윈도우 환경의 메모리 덤프로부터 닷넷 모듈을 추출하는 방법파일 다운로드1
13143정성태10/19/20226354오류 유형: 821. windbg/sos - Error code - 0x000021BE
13142정성태10/18/20225168도서: 시작하세요! C# 12 프로그래밍
13141정성태10/17/20226831.NET Framework: 2058. [in,out] 배열을 C#에서 C/C++로 넘기는 방법 - 세 번째 이야기파일 다운로드1
13140정성태10/11/20226214C/C++: 159. C/C++ - 리눅스 환경에서 u16string 문자열을 출력하는 방법 [2]
13139정성태10/9/20226022.NET Framework: 2057. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 모든 닷넷 모듈을 추출하는 방법파일 다운로드1
13138정성태10/8/20227335.NET Framework: 2056. C# - await 비동기 호출을 기대한 메서드가 동기로 호출되었을 때의 부작용 [1]
13137정성태10/8/20225675.NET Framework: 2055. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 닷넷 모듈을 추출하는 방법
13136정성태10/7/20226250.NET Framework: 2054. .NET Core/5+ SDK 설치 없이 dotnet-dump 사용하는 방법
13135정성태10/5/20226495.NET Framework: 2053. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프를 분석하는 방법 - 두 번째 이야기
13134정성태10/4/20225235오류 유형: 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/20225560Windows: 211. Windows - (commit이 아닌) reserved 메모리 사용량 확인 방법 [1]
13132정성태10/3/20225451스크립트: 42. 파이썬 - latexify-py 패키지 소개 - 함수를 mathjax 식으로 표현
13131정성태10/3/20228171.NET Framework: 2052. C# - Windows Forms의 데이터 바인딩 지원(DataBinding, DataSource) [2]파일 다운로드1
... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...