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




C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유

지난 글에서, SemaphoreSlim의 단점을 살펴봤는데요,

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

해당 글에서 예를 든 소스코드를 Mutex로 바꾸면 이렇게 작성할 수 있습니다.

internal class Program
{
    static Mutex _mutex = new Mutex(false);

    static void Main(string[] args)
    {
        for (int i = 0; i < 10; i++)
        {
            new Thread(() =>
            {
                Thread.Sleep(500);

                _mutex.WaitOne();

                try
                {
                    Console.WriteLine("Hello, Lock!");
                }
                finally
                {
                    try
                    { _mutex.ReleaseMutex(); }
                    catch { }
                }
            }).Start();
        }

        _mutex.WaitOne();
        Console.WriteLine("Hello, World!");

        Thread.Sleep(2000);

        _mutex.Dispose();
    }
}

Mutex도 단순히 Dispose만 하면 WaitHandle을 닫기만 하기 때문에 WaitOne으로 대기하던 스레드들의 lock이 풀리지 않은 채로 무한 대기를 하게 됩니다. 하지만, 다음과 같이 (별다른 고려 사항 없이) ReleaseMutex만 해주면,

_mutex.ReleaseMutex();
_mutex.Dispose();

SemaphoreSlim과는 달리 자연스럽게 모든 lock이 풀립니다. 즉, 위의 소스코드에서는 10개의 WaitOne이 모두 풀리게 됩니다.




혹시나, ReleaseMutex 호출을 잊어 다른 스레드들이 hang 상태로 빠졌다면 문제의 원인을 어떻게 추적할 수 있을까요? 우선, 그런 상태로 프로세스 덤프를 뜨면 "!handle" 명령어를 이용해 Mutex에 해당하는 자원을 다음과 같이 알아낼 수 있습니다.

// !handle [handle] [flags]
// flags == 0xf == dump detailed information

0:010> !handle 0 f Mutant
Handle c0
  ...[생략]...
Handle 00000000000001b4
  Type             Mutant
  Attributes   	0
  GrantedAccess	0x1f0001:
         Delete,ReadControl,WriteDac,WriteOwner,Synch
         QueryState
  HandleCount  	2
  PointerCount 	65533
  Name         	
  Object specific information
    Mutex is Free
    Mutant Owner 0.0
Handle 00000000000002b0
  Type             Mutant
  Attributes   	0
  GrantedAccess	0x1f0001:
         Delete,ReadControl,WriteDac,WriteOwner,Synch
         QueryState
  HandleCount  	2
  PointerCount 	65537
  Name         	
  Object specific information
    Mutex is Owned
    Mutant Owner a148.9c74
6 handles of type Mutant

위의 출력에는 2개의 Mutex가 있지만, 0x2b0 핸들만이 "Mutex is Owned"로, 특정 스레드가 lock을 소유하고 있음을 알 수 있습니다. 게다가 그 소유자의 프로세스 ID == a148, 스레드 ID == 9c74까지 알게 되었는데요, 만약 같은 스레드라면,

0:010> !threads
ThreadCount:      12
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 9c74 0000022765df1190  203a220 Preemptive  00000227679C8830:00000227679C9FD0 0000022765dc8330 0     MTA 
   5    2 4d70 0000022765e1a670    2b220 Preemptive  0000000000000000:0000000000000000 0000022765dc8330 0     MTA (Finalizer) 
   6    3 7c44 0000022765e439e0  202b020 Preemptive  00000227679C4020:00000227679C5FD0 0000022765dc8330 0     MTA 
   7    4 71a8 0000022765e46fe0  202b020 Preemptive  0000000000000000:0000000000000000 0000022765dc8330 0     MTA 
   8    5 8574 0000022765e49030  202b020 Preemptive  0000000000000000:0000000000000000 0000022765dc8330 0     MTA 
   9    6 7610 0000022765e4b080  202b020 Preemptive  0000000000000000:0000000000000000 0000022765dc8330 0     MTA 
  10    7 8610 0000022765e4d4e0  202b020 Preemptive  0000000000000000:0000000000000000 0000022765dc8330 0     MTA 
  11    8 5e84 0000022765e52550  202b020 Preemptive  0000000000000000:0000000000000000 0000022765dc8330 0     MTA 
  12    9 8c78 0000022765e569f0  202b020 Preemptive  0000000000000000:0000000000000000 0000022765dc8330 0     MTA 
  13   10 8968 0000022765e58ab0  202b020 Preemptive  0000000000000000:0000000000000000 0000022765dc8330 0     MTA 
  14   11 14a0 0000022765e5a360  202b020 Preemptive  0000000000000000:0000000000000000 0000022765dc8330 0     MTA 
  15   12 7678 0000022765e5da10  202b020 Preemptive  0000000000000000:0000000000000000 0000022765dc8330 0     MTA 

0번 스레드임을 바로 알 수 있고, 그것의 호출 스택을 통해,

0:010> !clrstack
OS Thread Id: 0x8610 (10)
        Child SP               IP Call Site
00000071595ff068 00007ff94504fec4 [HelperMethodFrame_1OBJ: 00000071595ff068] System.Threading.WaitHandle.WaitOneNative(System.Runtime.InteropServices.SafeHandle, UInt32, Boolean, Boolean)
00000071595ff190 00007ff91b9dddfc System.Threading.WaitHandle.InternalWaitOne(System.Runtime.InteropServices.SafeHandle, Int64, Boolean, Boolean) [f:\dd\ndp\clr\src\BCL\system\threading\waithandle.cs @ 243]
00000071595ff1c0 00007ff91b9dddcf System.Threading.WaitHandle.WaitOne(Int32, Boolean) [f:\dd\ndp\clr\src\BCL\system\threading\waithandle.cs @ 194]
00000071595ff200 00007ff8c8820be2 ConsoleApp2.Program+c.b__1_0() [C:\temp\MutexSample\ConsoleApp3\Program.cs @ 18]
00000071595ff270 00007ff91b98fbe8 System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) [f:\dd\ndp\clr\src\BCL\system\threading\executioncontext.cs @ 980]
00000071595ff340 00007ff91b98fad5 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) [f:\dd\ndp\clr\src\BCL\system\threading\executioncontext.cs @ 928]
00000071595ff370 00007ff91b98faa5 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object) [f:\dd\ndp\clr\src\BCL\system\threading\executioncontext.cs @ 917]
00000071595ff3c0 00007ff91b9b4435 System.Threading.ThreadHelper.ThreadStart() [f:\dd\ndp\clr\src\BCL\system\threading\thread.cs @ 111]
00000071595ff5e0 00007ff927ff12c3 [GCFrame: 00000071595ff5e0] 
00000071595ff948 00007ff927ff12c3 [DebuggerU2MCatchHandlerFrame: 00000071595ff948] 

hang을 유발한 코드를 유추할 수 있습니다. 혹은, hang에 걸려 있는 _mutex를 직접 분석하는 것도 가능합니다. 가령, 위의 코드에서는 _mutex가 Program 타입의 정적 변수로 정의돼 있는데요, 따라서 이를 추적해 보면,

0:010> !name2ee ConsoleApp3!ConsoleApp2.Program
Module:      00007ff8c87141b0
Assembly:    ConsoleApp3.exe
Token:       0000000002000002
MethodTable: 00007ff8c8715ad0
EEClass:     00007ff8c8712568
Name:        ConsoleApp2.Program

0:010> !DumpClass /d 00007ff8c8712568
Class Name:      ConsoleApp2.Program
mdToken:         0000000002000002
File:            C:\temp\MutexSample\ConsoleApp3\bin\Debug\ConsoleApp3.exe
Parent Class:    00007ff91b4348f0
Module:          00007ff8c87141b0
Method Table:    00007ff8c8715ad0
Vtable Slots:    4
Total Method Slots:  6
Class Attributes:    100000  
Transparency:        Critical
NumInstanceFields:   0
NumStaticFields:     1
              MT    Field   Offset                 Type VT     Attr            Value Name
00007ff91b495798  4000001        8 ...m.Threading.Mutex  0   static 00000227679c2e40 _mutex

0:010> !DumpObj /d 00000227679c2e40
Name:        System.Threading.Mutex
MethodTable: 00007ff91b495798
EEClass:     00007ff91b6a9260
Size:        48(0x30) 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
00007ff91b480b08  40005ba        8        System.Object  0 instance 0000000000000000 __identity
00007ff91b47f818  4001a53       18        System.IntPtr  1 instance              2b0 waitHandle
00007ff91b47e248  4001a54       10 ...es.SafeWaitHandle  0 instance 00000227679c2f68 safeWaitHandle
00007ff91b47c590  4001a55       20       System.Boolean  1 instance                1 hasThreadAffinity
00007ff91b47f818  4001a56      f70        System.IntPtr  1   shared           static InvalidHandle
                                 >> Domain:Value  0000022765dc8330:ffffffffffffffff <<
00007ff91b47c590  40019ab      f63       System.Boolean  1   shared           static dummyBool
                                 >> Domain:Value  0000022765dc8330:NotInit  <<

해당 Mutex 내의 핸들값이 0x2b0으로 나오고 이 값은 "!handle 0 f Mutant"로 출력된 것과 정확히 일치합니다.




따라서, 어차피 critical section을 보호하는 용도로 사용할 목적의 lock이라면 maxCount == 1 유형의 Semaphore를 다루는 것보다 Mutex 또는 lock(obj)으로 다루는 편이 문제가 발생했을 때 원인 파악을 위해서도 더 나은 선택입니다.

참고로, lock(obj)에 대한 글은 이전에 정리한 적이 있으니 이번 글에서는 생략합니다. ^^

windbg - C# Monitor Lock을 획득하고 있는 스레드 찾는 방법
; https://www.sysnet.pe.kr/2/0/11268

windbg - Monitor.Enter의 thin lock과 fat lock
; https://www.sysnet.pe.kr/2/0/13552

마지막으로, 기왕에 읽어본 김에 다음의 글도 마저 보시고. ^^

Who is blocking that Mutex? - Fun with WinDbg, CDB and KD
; https://archive.thinktecture.com/ingo/2006/08/who-is-blocking-that-mutex---fun-with-windbg-cdb-and-kd.html




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







[최초 등록일: ]
[최종 수정일: 2/18/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)
12604정성태4/18/20217425VS.NET IDE: 163. 비주얼 스튜디오 속성 창의 "Build(빌드)" / "Configuration(구성)"에서의 "활성" 의미
12603정성태4/16/20218308VS.NET IDE: 162. 비주얼 스튜디오 - 상속받은 컨트롤이 디자인 창에서 지원되지 않는 문제
12602정성태4/16/20219515VS.NET IDE: 161. x64 DLL 프로젝트의 컨트롤이 Visual Studio의 Designer에서 보이지 않는 문제 [1]
12601정성태4/15/20218602.NET Framework: 1040. C# - REST API 대신 github 클라이언트 라이브러리를 통해 프로그래밍으로 접근
12600정성태4/15/20218784.NET Framework: 1039. C# - Kubeconfig의 token 설정 및 인증서 구성을 자동화하는 프로그램
12599정성태4/14/20219488.NET Framework: 1038. C# - 인증서 및 키 파일로부터 pfx/p12 파일을 생성하는 방법파일 다운로드1
12598정성태4/14/20219603.NET Framework: 1037. openssl의 PEM 개인키 파일을 .NET RSACryptoServiceProvider에서 사용하는 방법 (2)파일 다운로드1
12597정성태4/13/20219688개발 환경 구성: 569. csproj의 내용을 공통 설정할 수 있는 Directory.Build.targets / Directory.Build.props 파일
12596정성태4/12/20219418개발 환경 구성: 568. Windows의 80 포트 점유를 해제하는 방법
12595정성태4/12/20218846.NET Framework: 1036. SQL 서버 - varbinary 타입에 대한 문자열의 CAST, CONVERT 변환을 C# 코드로 구현
12594정성태4/11/20218300.NET Framework: 1035. C# - kubectl 명령어 또는 REST API 대신 Kubernetes 클라이언트 라이브러리를 통해 프로그래밍으로 접근 [1]파일 다운로드1
12593정성태4/10/20219449개발 환경 구성: 567. Docker Desktop for Windows - kubectl proxy 없이 k8s 대시보드 접근 방법
12592정성태4/10/20219251개발 환경 구성: 566. Docker Desktop for Windows - k8s dashboard의 Kubeconfig 로그인 및 Skip 방법
12591정성태4/9/202112503.NET Framework: 1034. C# - byte 배열을 Hex(16진수) 문자열로 고속 변환하는 방법 [2]파일 다운로드1
12590정성태4/9/20219012.NET Framework: 1033. C# - .NET 4.0 이하에서 Console.IsInputRedirected 구현 [1]
12589정성태4/8/202110344.NET Framework: 1032. C# - Environment.OSVersion의 문제점 및 윈도우 운영체제의 버전을 구하는 다양한 방법 [1]
12588정성태4/7/202110939개발 환경 구성: 565. PowerShell - New-SelfSignedCertificate를 사용해 CA 인증서 생성 및 인증서 서명 방법
12587정성태4/6/202111728개발 환경 구성: 564. Windows 10 - ClickOnce 배포처럼 사용할 수 있는 MSIX 설치 파일 [1]
12586정성태4/5/20219413오류 유형: 710. Windows - Restart-Computer / shutdown 명령어 수행 시 Access is denied(E_ACCESSDENIED)
12585정성태4/5/20219188개발 환경 구성: 563. 기본 생성된 kubeconfig 파일의 내용을 새롭게 생성한 인증서로 구성하는 방법
12584정성태4/1/20219872개발 환경 구성: 562. kubeconfig 파일 없이 kubectl 옵션만으로 실행하는 방법
12583정성태3/29/202111378개발 환경 구성: 561. kubectl 수행 시 다른 k8s 클러스터로 접속하는 방법
12582정성태3/29/202110052오류 유형: 709. Visual C++ - 컴파일 에러 error C2059: syntax error: '__stdcall'
12581정성태3/28/20219990.NET Framework: 1031. WinForm/WPF에서 Console 창을 띄워 출력하는 방법 (2) - Output 디버깅 출력을 AllocConsole로 우회 [2]
12580정성태3/28/20218719오류 유형: 708. SQL Server Management Studio - Execution Timeout Expired.
12579정성태3/28/20218797오류 유형: 707. 중첩 가상화(Nested Virtualization) - The virtual machine could not be started because this platform does not support nested virtualization.
... 31  32  33  34  35  36  37  38  39  40  [41]  42  43  44  45  ...