Microsoft MVP성태의 닷넷 이야기
VC++: 79. [부연] CAS Lock 알고리즘은 과연 빠른가? [링크 복사], [링크+제목 복사],
조회: 25501
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

[부연] CAS Lock Lock-Free 알고리즘은 과연 빠른가?

아래와 같은 글이 있군요. ^^

Lock-Free 알고리즘은 과연 빠른가? 
; http://little-thread.blogspot.kr/2014/08/lock-free.html

결론은 CAS Lock lock-free보다 CriticalSection을 쓴 것이 더 빠르다는 것입니다.

그런데, 약간 테스트 상에 공정성이 위배되는 것이 있습니다. CriticalSection은 블록으로 썼으면서,

ULONGLONG t0 = ::GetTickCount64();
for (int i = 0; i < TEST_LOOP; i++) {
    ::EnterCriticalSection(&cs);
    volatile LONG* p = v;
    for (int j = 0; j < cntTest; j++) {
        _asm mov eax, p;
        _asm inc[eax];
        p++;
    }
    ::LeaveCriticalSection(&cs);
}

CAS Lock lock-free 쪽은 매순간 lock을 거는 방식을 썼습니다.

ULONGLONG t1 = ::GetTickCount64();
for (int i = 0; i < TEST_LOOP; i++) {
    volatile LONG* p = v;
    for (int j = 0; j < cntTest; j++) {
        _asm mov eax, p;
        _asm lock inc[eax];
        p++;
    }
}
    
ULONGLONG t2 = ::GetTickCount64();
for (int i = 0; i < TEST_LOOP; i++) {
    volatile LONG* p = v;
    for (int j = 0; j < cntTest; j++) 
    {
        ::InterlockedIncrement(p);
        p++;
    }
}

CAS Lock lock-free를 블록으로 사용하는 방법은 조금 미루고 바로 위에 소개한 2개의 테스트를 좀 볼까요? 우선 _asm으로 인라인 시킨 경우 실행시 기계어가 이렇고,

mov         eax,dword ptr [ebp-0C0h]  
lock inc    byte ptr [eax]  

InterlockedIncrement의 경우 결국 다음과 같은 기계어로 인라인 되므로,

mov         eax,dword ptr [ebp-0F4h]  
mov         ecx,1  
lock xadd   dword ptr [eax],ecx  

별반 큰 차이가 없습니다. 재미있는 것은 기계어가 오히려 1개 더 늘었는데도 "Lock-Free 알고리즘은 과연 빠른가?" 글에 공개된 수치를 보면 InterlockedIncrement의 성능이 근소하게 빠르다는 점입니다.

test =  1 : lock = 202, lock_free 1 = 110, lock_free 2 = 78
test =  2 : lock = 234, lock_free 1 = 171, lock_free 2 = 172
test =  3 : lock = 218, lock_free 1 = 250, lock_free 2 = 234
test =  4 : lock = 234, lock_free 1 = 343, lock_free 2 = 281
test =  5 : lock = 234, lock_free 1 = 437, lock_free 2 = 358
test =  6 : lock = 234, lock_free 1 = 515, lock_free 2 = 421
test =  7 : lock = 250, lock_free 1 = 593, lock_free 2 = 499
test =  8 : lock = 250, lock_free 1 = 686, lock_free 2 = 562
test =  9 : lock = 265, lock_free 1 = 733, lock_free 2 = 624
test = 10 : lock = 281, lock_free 1 = 811, lock_free 2 = 702




그나저나, CAS Lock lock-free를 블록으로 사용하는 방법이 뭘까요? 예전에 이에 대해 한번 소개해 드렸었지요. ^^

CAS Lock lock-free 방식이 과연 성능에 얼마나 도움이 될까요?
; https://www.sysnet.pe.kr/2/0/1458

저 역시 위의 글에서 C#의 경우 lock 코드가 CAS Lock lock-free보다 더 빠르다고 결론을 내렸었습니다. 따라서 저 글의 코드를 유사하게 가져다가 테스트를 할 수 있습니다.

volatile unsigned int _lockVariable = 0;
ULONGLONG t3 = ::GetTickCount64();
for (int i = 0; i < TEST_LOOP; i++) {
    volatile LONG* p = v;
    while (::InterlockedCompareExchange(&_lockVariable, 1, 0) != 0)
    {
    }

    for (int j = 0; j < cntTest; j++)
    {
        _asm mov eax, p;
        _asm inc[eax];
        p++;
    }

    _lockVariable = 0;
}

테스트 결과가 궁금하지 않으세요? ^^ 다음은 제 컴퓨터에서 수행한 것입니다.

test = 1 : lock = 203, lock_free 1 = 78, lock_free 2 = 78, lock_free 3 = 250
test = 2 : lock = 188, lock_free 1 = 125, lock_free 2 = 125, lock_free 3 = 265
test = 3 : lock = 203, lock_free 1 = 204, lock_free 2 = 187, lock_free 3 = 266
test = 4 : lock = 218, lock_free 1 = 250, lock_free 2 = 235, lock_free 3 = 281
test = 5 : lock = 219, lock_free 1 = 312, lock_free 2 = 297, lock_free 3 = 297
test = 6 : lock = 234, lock_free 1 = 360, lock_free 2 = 359, lock_free 3 = 313
test = 7 : lock = 234, lock_free 1 = 422, lock_free 2 = 422, lock_free 3 = 328
test = 8 : lock = 266, lock_free 1 = 500, lock_free 2 = 484, lock_free 3 = 359
test = 9 : lock = 266, lock_free 1 = 547, lock_free 2 = 547, lock_free 3 = 375
test = 10 : lock = 281, lock_free 1 = 609, lock_free 2 = 594, lock_free 3 = 391

오호~~~ 그래도 CriticalSection보다 성능이 낮군요. 그러나 이것은 DEBUG 빌드의 결과물입니다. Release 빌드로 하면 상황이 역전됩니다.

test = 1 : lock = 187, lock_free 1 = 78, lock_free 2 = 47, lock_free 3 = 109
test = 2 : lock = 204, lock_free 1 = 125, lock_free 2 = 109, lock_free 3 = 94
test = 3 : lock = 203, lock_free 1 = 187, lock_free 2 = 157, lock_free 3 = 78
test = 4 : lock = 203, lock_free 1 = 250, lock_free 2 = 203, lock_free 3 = 109
test = 5 : lock = 219, lock_free 1 = 313, lock_free 2 = 265, lock_free 3 = 94
test = 6 : lock = 203, lock_free 1 = 391, lock_free 2 = 312, lock_free 3 = 94
test = 7 : lock = 219, lock_free 1 = 453, lock_free 2 = 359, lock_free 3 = 110
test = 8 : lock = 218, lock_free 1 = 516, lock_free 2 = 406, lock_free 3 = 125
test = 9 : lock = 219, lock_free 1 = 594, lock_free 2 = 453, lock_free 3 = 125
test = 10 : lock = 219, lock_free 1 = 671, lock_free 2 = 500, lock_free 3 = 141

보시는 바와 같이 새롭게 추가한 "lock_free 3" 번의 결과는 CriticalSection 보다 성능이 더 좋습니다.

(첨부한 코드는 "Lock-Free 알고리즘은 과연 빠른가?" 글에 공개된 것에 블록 방식의 lock-free 코드를 추가한 것입니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/27/2023]

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

비밀번호

댓글 작성자
 



2014-08-26 12시13분
위에서 제가 제시한 방법은 엄밀히 lock-free라고 볼 수 없고, 그냥 CAS를 이용한 lock을 한 것에 불과합니다. lock-free에 대한 자세한 사항은 다음의 글을 참조하세요. ^^

Chapter 17. Boost.Lockfree
; http://www.boost.org/doc/libs/1_53_0/doc/html/lockfree.html

Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이 왜 이리 힘드나요? (Lock-free에서 Transactional Memory까지)
; http://www.slideshare.net/zzapuno/ndc2014-2
정성태
2021-05-15 11시48분
정성태

... 181  182  183  184  185  186  187  188  189  190  191  [192]  193  194  195  ...
NoWriterDateCnt.TitleFile(s)
135정성태3/31/200520887VS.NET IDE: 26. SQL Server 2000구성이 실패
134정성태3/31/200518095COM 개체 관련: 16. Microsoft.XMLHTTP 개체에서 Microsoft.XMLDOM 개체를 전송할 때 charset 지정 문제? [2]
128정성태3/30/200516458.NET Framework: 34. VC++에서 Managed 타입의 메서드에 BSTR을 넘기는 경우의 오류(!)
129정성태3/30/200518553    답변글 .NET Framework: 34.1. 위의 질문에 대한 답변으로 나온 것입니다.
130정성태3/30/200515884        답변글 .NET Framework: 34.2. 다시... 제가 질문한 내용입니다. ^^
131정성태3/30/200516379            답변글 .NET Framework: 34.3. 다시... 정봉겸님이 하신... 명확한 답변입니다.
126정성태3/26/200516231.NET Framework: 33. Proxy 환경에서의 Smart Client 업데이트 문제 [1]
133정성태3/31/200517374    답변글 .NET Framework: 33.1. [추가]: Proxy 환경에서의 Smart Client 업데이트 문제 [2]
125정성태3/26/200516353VC++: 15. VC++ Keyword
124정성태3/25/200516872.NET Framework: 32. 네트워크 공유 없이 상대 컴퓨터에 프로그램 설치
119정성태3/21/200516464.NET Framework: 31. 소스세이프 오류현상: 웹 프로젝트를 열수 없습니다.
120정성태3/21/200517756    답변글 .NET Framework: 31.1. 소스세이프 오류현상: PDB 파일이 잠기는 문제
121정성태3/21/200517825    답변글 .NET Framework: 31.2. 소스세이프 오류현상: VS.NET 2003 IDE 와 연동되는 소스세이프 버전 문제
122정성태3/21/200516514    답변글 .NET Framework: 31.3. 소스세이프 관련 사이트
160정성태11/14/200519398    답변글 VS.NET IDE: 31.4. [추가]: 웹 애플리케이션 로드시 "_1"을 붙여서 묻는 경우. [1]
196이문석12/23/200516212        답변글 .NET Framework: 31.8. [답변]: [추가]: 웹 애플리케이션 로드시 "_1" 을 붙여서 묻는 경우.
167정성태10/10/200515787    답변글 .NET Framework: 31.5. [추가]: 삭제한 웹 가상 디렉터리에 대해 동일한 이름으로 웹 공유를 설정할 때 - 이미 있다고 오류발생
190정성태12/11/200515096    답변글 VC++: 31.6. ASP.NET 소스세이프 오류현상: 다른 사람이 체크아웃 한 것을 또 다른 사람이 체크아웃 가능!
191정성태12/11/200517534    답변글 VC++: 31.7. 소스 세이프 사용 시, 특정 프로젝트의 빌드 체크가 솔루션 로드할 때마다 해제되는 경우
118정성태3/30/200623294VC++: 14. TCP through HTTP tunneling: 기업 내 Proxy 서버 제한에서 벗어나는 방법 [2]
117정성태3/19/200524408.NET Framework: 30. Process.Start에서의 인자 길이 제한 [4]
116정성태3/14/200516933.NET Framework: 29. [.NET WebService] 자동생성되는 WSDL 을 막는 방법.
115정성태3/13/200517439VS.NET IDE: 25. [IIS 서버] ODBC 로그 남기기 [1]
195정성태12/21/200516702    답변글 VC++: 25.1. ODBC 로그를 못 남길 때의 오류 화면
113정성태3/13/200517509VS.NET IDE: 24. [VPC] 타이머 동기화 기능 제거
110정성태11/14/200516448.NET Framework: 28. VS.NET 2005 / SQL Server 2005 베타 버전 재설치 또는 업그레이드 [1]
... 181  182  183  184  185  186  187  188  189  190  191  [192]  193  194  195  ...