Microsoft MVP성태의 닷넷 이야기
.NET Framework: 456. C# - CAS를 이용한 Lock 래퍼 클래스 [링크 복사], [링크+제목 복사],
조회: 21828
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - CAS를 이용한 Lock 래퍼 클래스

기왕 lock-free를 통해 CAS(Compare-And-Swap)을 다뤄본 김에,

[부연] Lock-Free 알고리즘은 과연 빠른가?
; https://www.sysnet.pe.kr/2/0/1736

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

간단하게 클래스로 래핑해 볼까요? ^^ 대충 다음과 같은 정도로 만들 수 있습니다.

public class CASLock : IDisposable // .NET IDisposable 처리 정리
                                    // ; https://www.sysnet.pe.kr/2/0/347
{
    int _lockVariable = 0;
    bool _disposed = true;

    public IDisposable Lock()
    {
        while (Interlocked.CompareExchange(ref _lockVariable, 1, 0) != 0) { }
        _disposed = false;
        return this;
    }

    void Free(bool disposing)
    {
        _lockVariable = 0;
        _disposed = true;
    }

    public void Dispose()
    {
        Free(true);
        GC.SuppressFinalize(this);
    }

    ~CASLock()
    {
#if DEBUG
        if (false == _disposed)
        {
            throw new ApplicationException("CASLock.Dispose() was not called!");
        }
#endif

        Free(false);
    }
}

사용법은 using을 통해 기존의 lock문과 거의 유사하게 쓸 수 있습니다.

CASLock lockA = new CASLock();

using (lockA.Lock())
{
    Console.WriteLine("locked");
}

전형적인 dead-lock 상황을 연출해 볼까요? ^^

using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace ConsoleApplication2
{
    class Program
    {
        CASLock lockA = new CASLock();
        CASLock lockB = new CASLock();

        static void Main(string[] args)
        {
            Program p = new Program();

            Thread t1 = new Thread(p.t1);
            Thread t2 = new Thread(p.t2);

            t1.Name = "lockAB";
            t2.Name = "lockBA";

            t1.Start();
            t2.Start();

            t1.Join(); // t1 스레드는 절대로 종료하지 않으므로 Join문은 반환하지 않음.
            t2.Join();
        }

        // Thread 1 
        void t1()
        {
            using (lockA.Lock())
            {
                Thread.Sleep(2000);
                using (lockB.Lock()) // Thread2의 t2메서드에서 이미 lock을 소유하고 있으므로 block
                {
                    Console.WriteLine("lockA -> lockB");
                }
            }
        }

        // Thread 2 
        void t2()
        {
            using (lockB.Lock())
            {
                Thread.Sleep(2000);
                using (lockA.Lock()) // Thread1의 t1메서드에서 이미 lock을 소유하고 있으므로 block
                {
                    Console.WriteLine("lockB -> lockA");
                }
            }
        }
    }
}

여기서, Thread.Abort 메서드로 특정 스레드를 강제 종료하는 것으로 우리가 만든 CASLock 클래스의 안정성 테스트를 해보겠습니다.

static void Main(string[] args)
{
    Program p = new Program();

    Thread t1 = new Thread(p.t1);
    Thread t2 = new Thread(p.t2);

    t1.Name = "lockAB";
    t2.Name = "lockBA";

    t1.Start();
    t2.Start();

    int retryCount = 5;
    while (retryCount-- > 0)
    {
        Console.Write(".");
        Thread.Sleep(1000);
    }

    t1.Abort(); // Thread1 강제 종료

    t1.Join();
    t2.Join();
}

테스트 코드를 실행시켜 보면 5초 후에 t1.Abort가 호출되고 이는 해당 스레드에 ThreadAbortException 예외를 발생시킵니다. 따라서 t1 메서드 내부의 using 문에서 IDisposable.Dispose 메서드가 실행되고 이로 인해 lockA의 잠금이 해제됩니다.

그런데, Native Win32 API인 TerminateThread를 호출하면 어떻게 될까요?

using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace ConsoleApplication2
{
    class Program
    {
        [DllImport("kernel32.dll")]
        static extern bool TerminateThread(IntPtr hThread, uint dwExitCode);

        [Flags]
        public enum ThreadAccess : int
        {
            TERMINATE = (0x0001),
        }

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, int dwThreadId);

        static IntPtr _threadAHandle = IntPtr.Zero;

        static void Main(string[] args)
        {
            Program p = new Program();

            Thread t1 = new Thread(p.t1);
            Thread t2 = new Thread(p.t2);

            t1.Name = "lockAB";
            t2.Name = "lockBA";

            t1.Start();
            t2.Start();

            int retryCount = 5;
            while (retryCount-- > 0)
            {
                Console.Write(".");
                Thread.Sleep(1000);
            }

            Console.WriteLine("Terminating...: " + Process.GetCurrentProcess().Threads.Count);
            TerminateThread(_threadAHandle, 100);
            Console.WriteLine("Terminated.: " + Process.GetCurrentProcess().Threads.Count);

            t1.Join();
            t2.Join();
        }

        CASLock lockA = new CASLock();
        CASLock lockB = new CASLock();


        // Thread 1 
        void t1()
        {
            _threadAHandle = OpenThread(ThreadAccess.TERMINATE, false, AppDomain.GetCurrentThreadId());
            using (lockA.Lock())
            {
                Thread.Sleep(2000);
                using (lockB.Lock())
                {
                    Console.WriteLine("lockA -> lockB");
                }
            }
        }

        // Thread 2 
        void t2()
        {
            using (lockB.Lock())
            {
                Thread.Sleep(2000);
                using (lockA.Lock())
                {
                    Console.WriteLine("lockB -> lockA");
                }
            }
        }
    }
}

이런 경우, Thread1이 종료되었음에도 불구하고 lock은 여전히 잠김상태로 남게 됩니다. (기존의 Monitor.Enter/Exit를 해도 동일하게 문제가 나타납니다.) 이는 LockFree 클래스의 안정성에 문제가 있는 것은 아니고 TerminateThread API는 때로 이렇게 위험한 상황을 연출하기 때문에 문서에는 다음과 같이 주의 사항이 나옵니다.

TerminateThread function
; https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-terminatethread

TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, TerminateThread can result in the following problems:
  • If the target thread owns a critical section, the critical section will not be released.
  • If the target thread is allocating memory from the heap, the heap lock will not be released.
  • If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
  • If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.
A thread cannot protect itself against TerminateThread, ...

보시는 것처럼, .NET 세계에서뿐만 아니라 Win32 SDK 세계에서도 TerminateThread API를 잘못 사용하면 저렇게 많은 문제를 발생할 수 있습니다. ^^ 한마디로, 모든 상황을 잘 이해하고 있지 않은 상황에서는 절대 써서는 안될 API입니다.

(첨부한 프로젝트는 위의 예제를 포함하고 있습니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 9/16/2023]

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

비밀번호

댓글 작성자
 




... [181]  182  183  184  185  186  187  188  189  190  191  192  193  194  195  ...
NoWriterDateCnt.TitleFile(s)
453정성태2/4/200724844개발 환경 구성: 21. 서버 측 SoapExtension을 클라이언트에 알리고 싶다
452정성태1/31/200724554VC++: 31. 비스타에서 VS.NET 2005로 COM 프로젝트 빌드시 오류 [2]
451정성태1/31/200723672Windows: 21. Preview Handler 소개
450정성태1/30/200731984VS.NET IDE: 43. .NET에서의 필수 무결성 제어 조절하는 방법 - Manifest 파일 이용파일 다운로드2
449정성태2/4/200728813Windows: 20. UAC 이모저모 [2]
448정성태1/28/200724474Windows: 19. 3가지 유형의 가젯 프로그램
447정성태1/27/200721676Windows: 18. 비스타 도구 - 사양 정보 및 도구(Performance Information and Tools)
446정성태1/27/200730566VC++: 30. 필수 무결성 제어를 조절하는 방법(2) - 직접 코딩파일 다운로드1
445정성태2/8/200729163VC++: 29. 필수 무결성 제어를 조절하는 방법(1) - Manifest 파일 이용파일 다운로드2
444정성태1/27/200722614VC++: 28. 비스타 응용 프로그램 개발을 위한 VS.NET 2005 환경 설정
443정성태1/26/200721108VC++: 27. COM 개체로 인해 IE 7 비스타 버전이 종료될 때 오류 화면이 뜬다면?파일 다운로드1
442정성태1/24/200724073.NET Framework: 79. 새로운 암호화 클래스 (ECDsaCng, ECDiffieHellmanCng) 소개 [1]
441정성태1/23/200728780Windows: 17. 보안 데스크톱에서 활성화되지 않은 UAC 창이 안전할까?
440정성태1/24/200722912.NET Framework: 78. C# 3.0 - Anonymous types [1]
439정성태1/25/200723912.NET Framework: 77. C# 3.0 - Lambda 표현식 [1]
438정성태1/24/200723424.NET Framework: 76. C# 3.0 - 확장 함수
437정성태1/23/200730861Windows: 16. 개발자를 위한 UAC 환경 설정 [3]
436정성태1/17/200720028VS.NET IDE: 42. Orcas 2007년 1월 CTP 버전 설치 [5]
435정성태1/14/200719692기타: 17. 베타 제품과 최종 제품은 다르다 [2]
434정성태2/4/200723260Windows: 15. MIC 환경 구성 - Windows XP와 유사한 보안 설정 [4]
433정성태1/12/200732801Windows: 14. 보호 모드와 필수 무결성 제어(MIC: Mandatory Integrity Control) [3]파일 다운로드1
432정성태1/10/200723904Windows: 13. InitOnceExecuteOnce API 소개 [5]
431정성태1/8/200721506Windows: 12. 비스타는 안전한 윈도우인가? [2]
430정성태1/7/200727402웹: 6. IIS 7 마이그레이션 정리 - Sysnet
427정성태12/30/200618116Team Foundation Server: 14. VS.NET IDE에 통합된 TFS Annotate [1]
425정성태12/29/200622059Windows: 11. Vista IIS 7(Integrated mode)에서의 ASP.NET F5 디버깅 방법
... [181]  182  183  184  185  186  187  188  189  190  191  192  193  194  195  ...