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

비밀번호

댓글 작성자
 




... 31  32  33  34  35  36  37  [38]  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12681정성태6/18/20217238오류 유형: 727. .NET 2.0 ~ 3.5 + x64 환경에서 System.EnterpriseServices 참조 시 CS8012 경고
12680정성태6/18/20218363오류 유형: 726. python2.7.exe 실행 시 0xc000007b 오류
12679정성태6/18/20218910COM 개체 관련: 23. CoInitializeSecurity의 전역 설정을 재정의하는 CoSetProxyBlanket 함수 사용법파일 다운로드1
12678정성태6/17/20218146.NET Framework: 1072. C# - CoCreateInstance 관련 Inteop 오류 정리파일 다운로드1
12677정성태6/17/20219655VC++: 144. 역공학을 통한 lxssmanager.dll의 ILxssSession 사용법 분석파일 다운로드1
12676정성태6/16/20219701VC++: 143. ionescu007/lxss github repo에 공개된 lxssmanager.dll의 CLSID_LxssUserSession/IID_ILxssSession 사용법파일 다운로드1
12675정성태6/16/20217732Java: 20. maven package 명령어 결과물로 (war가 아닌) jar 생성 방법
12674정성태6/15/20218512VC++: 142. DEFINE_GUID 사용법
12673정성태6/15/20219648Java: 19. IntelliJ - 자바(Java)로 만드는 Web App을 Tomcat에서 실행하는 방법
12672정성태6/15/202110805오류 유형: 725. IntelliJ에서 Java webapp 실행 시 "Address localhost:1099 is already in use" 오류
12671정성태6/15/202117522오류 유형: 724. Tomcat 실행 시 Failed to initialize connector [Connector[HTTP/1.1-8080]] 오류
12670정성태6/13/20219052.NET Framework: 1071. DLL Surrogate를 이용한 Out-of-process COM 개체에서의 CoInitializeSecurity 문제파일 다운로드1
12669정성태6/11/20219027.NET Framework: 1070. 사용자 정의 GetHashCode 메서드 구현은 C# 9.0의 record 또는 리팩터링에 맡기세요.
12668정성태6/11/202110803.NET Framework: 1069. C# - DLL Surrogate를 이용한 Out-of-process COM 개체 제작파일 다운로드2
12667정성태6/10/20219447.NET Framework: 1068. COM+ 서버 응용 프로그램을 이용해 CoInitializeSecurity 제약 해결파일 다운로드1
12666정성태6/10/20218027.NET Framework: 1067. 별도 DLL에 포함된 타입을 STAThread Main 메서드에서 사용하는 경우 CoInitializeSecurity 자동 호출파일 다운로드1
12665정성태6/9/20219312.NET Framework: 1066. Wslhub.Sdk 사용으로 알아보는 CoInitializeSecurity 사용 제약파일 다운로드1
12664정성태6/9/20217606오류 유형: 723. COM+ PIA 참조 시 "This operation failed because the QueryInterface call on the COM component" 오류
12663정성태6/9/20219138.NET Framework: 1065. Windows Forms - 속성 창의 디자인 설정 지원: 문자열 목록 내에서 항목을 선택하는 TypeConverter 제작파일 다운로드1
12662정성태6/8/20218265.NET Framework: 1064. C# COM 개체를 PIA(Primary Interop Assembly)로써 "Embed Interop Types" 참조하는 방법파일 다운로드1
12661정성태6/4/202118908.NET Framework: 1063. C# - MQTT를 이용한 클라이언트/서버(Broker) 통신 예제 [4]파일 다운로드1
12660정성태6/3/202110007.NET Framework: 1062. Windows Forms - 폼 내에서 발생하는 마우스 이벤트를 자식 컨트롤 영역에 상관없이 수신하는 방법 [1]파일 다운로드1
12659정성태6/2/202111269Linux: 40. 우분투 설치 후 MBR 디스크 드라이브 여유 공간이 인식되지 않은 경우 - Logical Volume Management
12658정성태6/2/20218682Windows: 194. Microsoft Store에 있는 구글의 공식 Youtube App
12657정성태6/2/202110010Windows: 193. 윈도우 패키지 관리자 - winget 설치
12656정성태6/1/20218228.NET Framework: 1061. 서버 유형의 COM+에 적용할 수 없는 Server GC
... 31  32  33  34  35  36  37  [38]  39  40  41  42  43  44  45  ...