Microsoft MVP성태의 닷넷 이야기
닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock [링크 복사], [링크+제목 복사],
조회: 9788
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)
(시리즈 글이 3개 있습니다.)
디버깅 기술: 92. windbg - C# Monitor Lock을 획득하고 있는 스레드 찾는 방법
; https://www.sysnet.pe.kr/2/0/11268

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

닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
; https://www.sysnet.pe.kr/2/0/13553




windbg - Monitor.Enter의 thin lock과 fat lock

마침 아래와 같은 좋은 글이 있어,

Managed object internals, Part 2. Object header layout and the cost of locking
; https://devblogs.microsoft.com/premier-developer/managed-object-internals-part-2-object-header-layout-and-the-cost-of-locking/

Sync Block Index (SBI) \ Object Header Word
; https://yonifedaeli.blogspot.com/2017/03/sync-block-index-sbi-object-header-word.html

소개하려고 합니다. (그대로 베낍니다. ^^)




예를 들어, 다음과 같이 코드를 작성 후,

using System.Threading;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            object o = new object();
            lock (o)
            {
                Debugger.Break();
            }
        }
    }
}

windbg를 이용해 실행한 다음 (처음 한 번은 'g' 키를 눌러 진행해) Debugger.Break에서 멈추었을 때 thinlock 상태를 확인할 수 있습니다.

0:000> !dumpheap -thinlock
         Address               MT     Size
000001d125c02e38 00007fffea220b08       24 ThinLock owner 1 (000001d1241a2970) Recursive 0
Found 1 objects.

0:000> !DumpObj /d 000001d125c02e38
Name:        System.Object
MethodTable: 00007fffea220b08
EEClass:     00007fffea1d48f0
Size:        24(0x18) bytes
File:        C:\WINDOWS\Microsoft.Net\assembly\GAC_64\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll
Object
Fields:
None
ThinLock owner 1 (000001d1241a2970), Recursive 0

thinlock 상태에서는 별도의 SyncBlock이 생성되지 않으므로 sos의 syncblk 명령어를 사용하면 비어있는 것을 볼 수 있습니다.

0:000> !syncblk
Index SyncBlock MonitorHeld Recursion Owning Thread Info  SyncBlock Owner
-----------------------------
Total           0
CCW             0
RCW             0
ComClassFactory 0
Free            0

즉, thinlock은 lock이 경합을 벌이지 않는 상태라면 성능을 위해 별도의 SyncBlock을 생성하지 않고 Object Header 내에만 정보를 유지하는 단계인 것입니다. 실제로 이 상태의 해당 object, 위의 소스코드에서는 "o" 인스턴스를 확인해 보면,

0:000> dq 000001d125c02e38-8 L3
000001d1`25c02e30  00000001`00000000 00007fff`ea220b08
000001d1`25c02e40  00000000`00000000

하위 값이 0x00000001로 나오는데, 이 상태의 의미를 확인해 보면,

0000 0000 0000 0000 0000 0000 0000 0001
|||| ||- BIT_SBLK_IS_HASHCODE
|||| |- BLT_SBLK_IS_HASH_OR_SYNCBLOCKINDEX
||||-BIT_SBLK_SPIN_LOCK
|||- BIT_SBLK_GC_RESERVE
||- BIT_SBLK_FINALIZER_RUN
|- BIT_SBLK_AGILE_IN_PROGRESS

[이미지 출처: "Managed object internals, Part 2. Object header layout and the cost of locking"]
object_header_syncblk_0.png

0~10비트: thread id that’s holding the lock

[이미지 출처: "Managed object internals, Part 2. Object header layout and the cost of locking"]
object_header_syncblk_1.png

해당 lock을 소유하고 있는 스레드 ID가 1로 나오는데 이를 !threads로 알아낼 수 있습니다.

0:009> !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 cfa0 000001d1241a2970  202a020 Preemptive  0000025ECD2A65C8:0000025ECD2A7FD0 0000025ecb632c70 0     MTA 
   5    2 bf60 0000015ecb6bcf90    2b220 Preemptive  0000000000000000:0000000000000000 0000025ecb632c70 0     MTA (Finalizer) 

따라서, 특정 lock이 thinlock 상태라면 1) 한 번도 다른 스레드에서 lock 경합을 벌인 적이 없거나, 2) 경합을 벌였어도 일정 spin 타임 내에 있는 경우가 됩니다. (이 외에도, GetHashCode를 부른 적이 없어야 합니다.)

자, 그럼 일부러 경합을 벌여보면,

static void Main(string[] args)
{
    object o = new object();
    lock (o)
    {
        Task.Run(() =>
        {
            // This will promote a thin lock as well
            lock (o) { }
        });

        // 10 ms is not enough, the CLR spins longer than 10 ms.
        Thread.Sleep(100);
        Debugger.Break();
    }
}

이제는 syncblk이 생성된 것을 볼 수 있고,

0:009> !dumpheap -thinlock
         Address               MT     Size
Found 0 objects.

0:000> !syncblk
Index SyncBlock MonitorHeld Recursion Owning Thread Info  SyncBlock Owner
    6 000002de0f4a8838            3         1 000002de0f452980 7e48   0   000002de10f52e50 System.Object
-----------------------------
Total           6
CCW             1
RCW             2
ComClassFactory 0
Free            0

인스턴스 'o'에 대해 Object Header를 조사해 보면,

0:000> dq 000002de10f52e50-8 L3
000002de`10f52e48  08000006`00000000 00007fff`ea220b08
000002de`10f52e58  00000000`00000000

0x08000006
0000 1000 0000 0000 0000 0000 0000 0110
|||| ||- BIT_SBLK_IS_HASHCODE
|||| |- BLT_SBLK_IS_HASH_OR_SYNCBLOCKINDEX (== 0x08000000)
||||-BIT_SBLK_SPIN_LOCK
|||- BIT_SBLK_GC_RESERVE
||- BIT_SBLK_FINALIZER_RUN
|- BIT_SBLK_AGILE_IN_PROGRESS

[이미지 출처: "Managed object internals, Part 2. Object header layout and the cost of locking"]
object_header_syncblk_2.png

BLT_SBLK_IS_HASH_OR_SYNCBLOCKINDEX 플래그가 1로 설정돼 있으므로 이하 (BIT_SBLK_IS_HASHCODE를 제외한) 0~25 비트의 값이 Sync Block에 대한 인덱스를 가리키게 됩니다. 위의 경우 그 값은 6이고, !syncblk 명령어의 결과에 있는 Index 값에 정확히 일치합니다.




참고로, 예전에 썼던 글의 내용에서,

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

lock을 대기 중인 스레드의 kv 결과로 어떤 SyncBlock에 걸려 있는지를 알아낼 수 있다고 했는데요, 이번에 다시 해보니,

0:009> kv
 # Child-SP          RetAddr               : Args to Child                                                           : Call Site
00 000000f4`222fe5b8 00007ff8`0a08f6f9     : 000002de`296fa3d0 000002de`296fa3e0 000002de`0f3c0000 00007ff8`0c9f6f52 : ntdll!NtWaitForMultipleObjects+0x14
01 000000f4`222fe5c0 00007fff`f0311636     : 00000000`00000000 00007fff`00000000 00000000`ffffffff 000002de`0f4a8850 : KERNELBASE!WaitForMultipleObjectsEx+0xe9
02 000000f4`222fe8a0 00007fff`f031102a     : 00000000`00000001 00000000`00000001 00000000`00000000 00007ff8`0c92ab11 : clr!WaitForMultipleObjectsEx_SO_TOLERANT+0x62
03 000000f4`222fe900 00007fff`f0310e01     : 00007fff`00000001 00007fff`00000001 00000000`00000001 00007fff`00000000 : clr!Thread::DoAppropriateWaitWorker+0x206
04 000000f4`222fe9f0 00007fff`f0283157     : 000002de`0f4a8850 00000000`00000001 000002de`0f4a8838 000002de`10f52e00 : clr!Thread::DoAppropriateWait+0x7d
05 000000f4`222fea70 00007fff`f06d93ee     : 000000f4`222fedf0 00000000`00000000 000002de`296f3860 00007fff`ea221740 : clr!CLREventBase::WaitEx+0xab
06 000000f4`222feae0 00007fff`f06d92a2     : 000002de`0f4a8838 00007fff`f02c735b 000002de`0f4a8838 000002de`10f52e50 : clr!AwareLock::EnterEpilogHelper+0x11a
07 000000f4`222feba0 00007fff`f05ee5a9     : 000002de`296f3860 000002de`0f4a8838 00000000`00000000 000000f4`222fedf0 : clr!AwareLock::EnterEpilog+0x5a
...[생략]...

CLREventBase::WaitEx에는 값이 안 나오고, AwareLock::EnterEpilogHelper 등의 "Args to Child"에서 확인할 수 있었습니다. (이 값은 닷넷 패치 버전에 따라서도 달라질 수 있기 때문에 항상 그렇다고 가정해서는 안 됩니다.)




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

[연관 글]






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

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

비밀번호

댓글 작성자
 




... 91  92  93  94  95  96  97  98  99  100  101  102  [103]  104  105  ...
NoWriterDateCnt.TitleFile(s)
11391정성태12/7/201721888개발 환경 구성: 340. WSL을 이용해 윈도우 PC 1대에서 openSUSE 응용 프로그램을 Visual Studio로 개발하는 방법 [1]
11390정성태12/7/201730774개발 환경 구성: 339. WSL을 이용해 윈도우 PC 1대에서 Linux 응용 프로그램을 Visual Studio로 개발하는 방법 [6]
11389정성태12/7/201719425오류 유형: 440. .NET Core 오류 - 0x80131620 Unable to load DLL 'libuv'
11388정성태12/6/201723217개발 환경 구성: 338. WSL 또는 Ubuntu에 닷넷 코어 설치 [3]
11387정성태12/6/201723193오류 유형: 439. 이벤트 로그 - Data Sharing Service 서비스의 %%3239247874 오류 메시지
11386정성태12/5/201719176오류 유형: 438. Hyper-V - '...' failed to add device 'Virtual CD/DVD Disk'
11385정성태12/5/201732354VC++: 121. DXGI를 이용한 윈도우 화면 캡처 소스 코드(Visual C++) [16]파일 다운로드1
11384정성태12/5/201721741오류 유형: 437. Visual C++ - Cannot open include file: 'SDKDDKVer.h'
11383정성태12/4/201724472디버깅 기술: 110. 비동기 코드 실행 중 예외로 인한 ASP.NET 프로세스 비정상 종료 현상 [1]
11382정성태12/4/201723159오류 유형: 436. System.Data.SqlClient.SqlException (0x80131904): Connection Timeout Expired 예외 발생 시 "[Pre-Login] initialization=48; handshake=1944;" 값의 의미
11381정성태11/30/201719713.NET Framework: 702. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법(두 번째 이야기)파일 다운로드1
11380정성태11/30/201719823디버깅 기술: 109. windbg - (x64에서의 인자 값 추적을 이용한) Thread.Abort 시 대상이 되는 스레드를 식별하는 방법
11379정성태11/30/201719798오류 유형: 435. System.Web.HttpException - Session state has created a session id, but cannot save it because the response was already flushed by the application.
11378정성태11/29/201721629.NET Framework: 701. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법 [1]파일 다운로드1
11377정성태11/29/201721207.NET Framework: 700. CommonOpenFileDialog 사용 시 사용자가 선택한 파일 목록을 구하는 방법 [3]파일 다운로드1
11376정성태11/28/201725795VS.NET IDE: 123. Visual Studio 편집기의 \r\n (crlf) 개행을 \n으로 폴더 단위로 설정하는 방법
11375정성태11/28/201719706오류 유형: 434. Visual Studio로 ASP.NET 디버깅 중 System.Web.HttpException - Could not load type 오류
11374정성태11/27/201725557사물인터넷: 14. 라즈베리 파이 - (윈도우의 NT 서비스처럼) 부팅 시 시작하는 프로그램 설정 [1]
11373정성태11/27/201724584오류 유형: 433. Raspberry Pi/Windows 다중 플랫폼 지원 컴파일 관련 오류 기록
11372정성태11/25/201727258사물인터넷: 13. 윈도우즈 사용자를 위한 라즈베리 파이 제로 W 모델을 설정하는 방법 [4]
11371정성태11/25/201721001오류 유형: 432. Hyper-V 가상 스위치 생성 시 Failed to connect Ethernet switch port 0x80070002 오류 발생
11370정성태11/25/201721201오류 유형: 431. Hyper-V의 Virtual Switch 생성 시 "External network" 목록에 특정 네트워크 어댑터 항목이 없는 경우
11369정성태11/25/201722922사물인터넷: 12. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드 및 마우스로 쓰는 방법 (절대 좌표, 상대 좌표, 휠) [1]
11368정성태11/25/201728353.NET Framework: 699. UDP 브로드캐스트 주소 255.255.255.255와 192.168.0.255의 차이점과 이를 고려한 C# UDP 서버/클라이언트 예제 [2]파일 다운로드1
11367정성태11/25/201728890개발 환경 구성: 337. 윈도우 운영체제의 route 명령어 사용법
11366정성태11/25/201720805오류 유형: 430. 이벤트 로그 - Cryptographic Services failed while processing the OnIdentity() call in the System Writer Object.
... 91  92  93  94  95  96  97  98  99  100  101  102  [103]  104  105  ...