Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2065. C# - Mutex의 비동기 버전 [링크 복사], [링크+제목 복사],
조회: 14579
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 7개 있습니다.)
.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

닷넷: 2284. C# - async 메서드에서의 lock/Monitor.Enter/Exit 잠금 처리
; https://www.sysnet.pe.kr/2/0/13697

닷넷: 2285. C# - async 메서드에서의 System.Threading.Lock 잠금 처리
; https://www.sysnet.pe.kr/2/0/13698




C# - Mutex의 비동기 버전

재미있는 글이 있군요. ^^

Async Mutex
; https://dfederm.com/async-mutex/

사실 위의 내용을 다루려고 이전 글에서 뮤텍스와 세마포어를 미리 다뤄야만 했습니다. ^^

C# - Mutex와 Semaphore/SemaphoreSlim 차이점
; https://www.sysnet.pe.kr/2/0/13156

간단하게 테스트를 해볼까요? ^^ 우선 Mutex를 쓰지 않는 버전으로 이렇게 작성한 후,

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Task t1 = Task.Run(async () =>
            {
                await PrintOut();
            });

            Task t2 = Task.Run(async () =>
            {
                await PrintOut();
            });

            t1.Wait();
            t2.Wait();
        }

        static async Task PrintOut()
        {
            Console.WriteLine($"{DateTime.Now:T} [{Thread.CurrentThread.ManagedThreadId}]: PrintOut-EX-before");
            Thread.Sleep(2000);
            Console.WriteLine($"{DateTime.Now:T} [{Thread.CurrentThread.ManagedThreadId}]: PrintOut-EX-after");
        }
    }
}

실행하면 다음과 같은 결과를 볼 수 있습니다.

오전 9:36:40 [7]: PrintOut-EX-before
오전 9:36:40 [6]: PrintOut-EX-before
오전 9:36:42 [6]: PrintOut-EX-after
오전 9:36:42 [7]: PrintOut-EX-after

예상 가능한 출력이죠? ^^ 자, 여기다 이제 비동기 mutex를 장착하면,

namespace ConsoleApp1
{
    internal class Program
    {
        static AsyncMutex m = new AsyncMutex(@"Global\MyMutex");

        // ...[생략]...

        static async Task PrintOut()
        {
            await m.AcquireAsync(CancellationToken.None);
            // ...[생략]...
            await m.ReleaseAsync();
        }
    }
}

Mutex의 영향으로 PrintOut 내부의 코드가 동기화돼 다음과 같은 출력 결과가 나옵니다.

오전 9:37:27 [11]: PrintOut-EX-before
오전 9:37:30 [11]: PrintOut-EX-after
오전 9:37:30 [12]: PrintOut-EX-before
오전 9:37:32 [12]: PrintOut-EX-after

잘 동작하는군요. ^^




그런데, 뭔가 좀 아쉽습니다. AsyncMutex의 소스 코드를 보면 AcquireAsync에서 Task.Factory.StartNew를 사용해 동기 작업에 해당하는 부분을 스레드로 감싸 비동기 처리하고 있습니다.

이런 처리를 스레드 없이 할 수도 있지 않을까요? 그렇습니다. 예전에 설명했던 방식을 곁들이면,

C# - CLR ThreadPool의 I/O 스레드에 작업을 맡기는 방법
; https://www.sysnet.pe.kr/2/0/13059

명시적인 스레드 사용 없이 다음과 같은 식으로 커널 개체가 Signaled 상태로 바뀌는 알림을 받아, 이후의 실행을 I/O 스레드에 맡겨보는 것도... 생각해 볼 수 있습니다.

namespace ConsoleApp1
{
    internal class AsyncMutex2
    {
        Mutex _m;

        public AsyncMutex2()
        {
            _m = new Mutex(false);
        }

        public AsyncMutex2(string name)
        {
            _m = new Mutex(false, name);
        }

        public Task AcquireAsync()
        {
            TaskCompletionSource taskCompletionSource = new();
            ThreadPool.RegisterWaitForSingleObject(_m, signalWork, taskCompletionSource, -1, true);
            return taskCompletionSource.Task;
        }

        public void Release()
        {
            _m.ReleaseMutex();
        }

        void signalWork(object? state, bool timedOut)
        {
            if (state is TaskCompletionSource taskSource)
            {
                taskSource.SetResult();
            }
        }
    }
}

하지만, 이런 구현은 유효하지 않습니다. "Async Mutex" 글의 저자도 이 부분에 대해 언급했는데요,

Mutexes have thread affinity; that is, the mutex can be released only by the thread that owns it.

지난번 글에 정리한 것처럼, Mutex는 WaitOne을 호출한 스레드에서 반드시 ReleaseMutex를 호출해야 하므로 await로 인해 스레드가 달라지는 상황에서는,

static async Task PrintOut()
{
    await m.AcquireAsync(); // 내부에서 WaitOne을 호출하는 스레드와,
    Console.WriteLine($"{DateTime.Now:T} [{Thread.CurrentThread.ManagedThreadId}]: PrintOut-EX-before");
    Thread.Sleep(2000);
    Console.WriteLine($"{DateTime.Now:T} [{Thread.CurrentThread.ManagedThreadId}]: PrintOut-EX-after");
    m.Release(); // 이곳에서 ReleaseMutex 호출하는 스레드는 I/O 스레드 풀로부터 가져온 것이므로.
}

결국 ReleaseMutex에서 "Object synchronization method was called from an unsynchronized block of code" 예외가 발생하는 것입니다.




이런 문제를 (Mutex처럼 사용할 수 있는) Semaphore를 이용하면 해결할 수 있습니다.

namespace ConsoleApp1
{
    internal class AsyncMutex2 : IAsyncDisposable
    {
        Semaphore _smp;

        public AsyncMutex2(string name)
        {
            _smp = new Semaphore(1, 1, name);
        }

        public Task AcquireAsync()
        {
            return AcquireAsync(-1);
        }

        public Task AcquireAsync(int millisecondsTimeOutInterval)
        {
            TaskCompletionSource taskCompletionSource = new();

            ThreadPool.RegisterWaitForSingleObject(_smp, signalWork, taskCompletionSource, millisecondsTimeOutInterval, true);
            return taskCompletionSource.Task;
        }

        public void Release()
        {
            _smp.Release();
        }

        void signalWork(object? state, bool timedOut)
        {
            if (state is TaskCompletionSource taskSource)
            {
                if (timedOut)
                {
                    taskSource.SetCanceled();
                    return;
                }

                taskSource.SetResult();
            }
        }

        public ValueTask DisposeAsync()
        {
            _smp.Dispose();
            return ValueTask.CompletedTask;
        }
    }
}

실제로 위의 코드를 사용하면,

static AsyncMutex2 m = new AsyncMutex2(@"Global\MyMutex");

static void Main(string[] args)
{
    Task t1 = Task.Run(async () =>
    {
        await PrintOut(1);
    });

    Task t2 = Task.Run(async () =>
    {
        await PrintOut(2);
    });

    Task t3 = Task.Run(async () =>
    {
        await PrintOut(3, 1000);
    });

    try
    {
        Task.WaitAll(t1, t2, t3);
    } catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

    Task t4 = Task.Run(async () =>
    {
        await PrintOut(4);
    });

    Task t5 = Task.Run(async () =>
    {
        await PrintOut(5);
    });

    Task.WaitAll(t4, t5);
}

static async Task PrintOut(int workId)
{
    await PrintOut(workId, -1);
}

static async Task PrintOut(int workId, int timeOut)
{
    await m.AcquireAsync(timeOut);
    Console.WriteLine($"{DateTime.Now} {workId} [{Thread.CurrentThread.ManagedThreadId}]: PrintOut-EX-before");
    Thread.Sleep(2000);
    Console.WriteLine($"{DateTime.Now} {workId} [{Thread.CurrentThread.ManagedThreadId}]: PrintOut-EX-after");
    m.Release();
}

잘 동작합니다.

2022-11-05 오후 1:28:38 1 [12]: PrintOut-EX-before
2022-11-05 오후 1:28:40 1 [12]: PrintOut-EX-after
2022-11-05 오후 1:28:40 2 [14]: PrintOut-EX-before
2022-11-05 오후 1:28:42 2 [14]: PrintOut-EX-after
One or more errors occurred. (A task was canceled.) // 3번 work는 1000ms 대기 시간을 초과해 취소됨
2022-11-05 오후 1:28:42 4 [14]: PrintOut-EX-before
2022-11-05 오후 1:28:44 4 [14]: PrintOut-EX-after
2022-11-05 오후 1:28:44 5 [14]: PrintOut-EX-before
2022-11-05 오후 1:28:46 5 [14]: PrintOut-EX-after

위에서 구현한 Mutex는 Semaphore를 바탕으로 구현했으므로 기반 동작은 세마포어의 특성을 띕니다. 그렇긴 해도 어차피 "Async Mutex" 글의 AsyncMutex도 결국 원래 Mutex의 고유 성격인 "재진입"을 허용하지 않으므로,

namespace ConsoleApp1
{
    internal class Program
    {
        static AsyncMutex m = new AsyncMutex(@"Global\MyMutex");

        // ...[생략]...

        static async Task PrintOut()
        {
            await m.AcquireAsync(CancellationToken.None);
            await m.AcquireAsync(CancellationToken.None); // 재진입 불가능 - hang!!!!
            // ...[생략]...
            await m.ReleaseAsync();
            await m.ReleaseAsync();
        }
    }
}

오히려 스레드 낭비 없는 AsyncMutex2 버전이 더 나을 것입니다. ^^




(AsyncMutex는 named mutex를 사용했고) AsyncMutex2 버전은 named Semaphore를 사용하고 있습니다. 왜냐하면 unnamed는 어차피 SemaphoreSlim에서 이미 비동기 버전의 WaitAsync를 제공하기 때문에 그것을 사용하면 됩니다.

static async Task Main(string[] args)
{
    SemaphoreSlim ss = new SemaphoreSlim(1, 1);
            
    await ss.WaitAsync();
    ss.Release();
}

따라서, 굳이 named일 필요가 없다면 SemaphoreSlim으로 간단하게 해결하시면 됩니다.

물론, 이것 역시 Mutex/Semaphore의 차이점이 허용된다는 가정이 성립할 때만 기존의 Mutex 코드를 안전하게 비동기로 바꿀 수 있을 것입니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




참고로, 찾아보니 RegisterWaitForSingleObject에 Mutex를 사용할 수 없다는 글을 누가 이미 써놨군요. ^^

RegisterWaitForSingleObject and mutexes don't mix
; http://joeduffyblog.com/2007/05/13/registerwaitforsingleobject-and-mutexes-dont-mix/




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







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

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)
92정성태1/29/200518238.NET Framework: 23. Unmanaged 환경에서 Managed DLL에 정의된 메서드 호출 시 오류 확인하는 방법
91정성태11/14/200518838VC++: 12. VS.NET 2005 VC++ Debug: Expression: ( (state != ST_INVALID ) )
90정성태1/27/200519620.NET Framework: 22. Debug: The underlying connection was closed: Unable to connect to the remote server.
89정성태1/26/200524155VC++: 11. Delay Loaded DLL
87정성태1/23/200517759VS.NET IDE: 18. VS.NET 2005 Beta 1 - VC++ 프로젝트에서 Connection Point 구현시 버그
88정성태1/23/200517461    답변글 VS.NET IDE: 18.1. VS.NET 2003 : VC++ 프로젝트에서 Connection Point 추가시에도 버그
86정성태1/23/200523178.NET Framework: 21. Code Snippet - Enum과 관련된 다양한 형변환 [1]
85정성태1/23/200521308스크립트: 4. Windows 2003에서 BHO(Browser Helper Objects) 동작 안하는 현상 [1]
83정성태1/18/200526450.NET Framework: 20. System.AccessViolationException 예외가 발생한 한 예.
82정성태1/3/200519916VS.NET IDE: 17. Windows 운영 - 특정 사용자 또는 그룹에 대해서 파일 공유 접근 금지
79정성태1/20/200527857기타: 8. DELL Latitude D800 노트북 컴퓨터의 PC Beep 소음(!) 문제.
78정성태12/27/200420227VS.NET IDE: 16. MS 제품 관련 사용되는 TCP/IP 포트 열거파일 다운로드1
77정성태12/27/200420479VS.NET IDE: 15. Virtual CD-ROM Control Panel - ISO 이미지를 CD-ROM 드라이브처럼 접근하게 해주는 EXE 프로그램 [1]파일 다운로드1
76정성태12/27/200421536VS.NET IDE: 14. VPN 접속시 IP를 고정적으로 할당받는 방법 [1]
75정성태12/27/200417778VS.NET IDE: 13. VS.NET 2005 Beta 1 - Portfolio Explorer 에 등록된 Team Server 항목 삭제 방법
84정성태1/19/200518654    답변글 VS.NET IDE: 13.1. VS.NET 2005 Beta 1 : Team Server 에 등록된 포트폴리오 프로젝트 삭제 방법
74정성태12/26/200419277VS.NET IDE: 12. [시나리오] VS.NET 2005 Team Foundation Server을 Virtual Server에 설치 [1]
80정성태12/31/200418561    답변글 VS.NET IDE: 12.1. Client Tier, 즉 VS.NET 2005가 설치된 컴퓨터도 ActiveDirectory에 참여를 해야 합니다.
81정성태12/31/200420472    답변글 VS.NET IDE: 12.2. Tier 컴퓨터를 모두 영문으로 재구성
109정성태3/4/200515674    답변글 VS.NET IDE: 12.3. [보완] MS 공식 아티클 - Installing the December CTP Release of Visual Studio Team System
73정성태11/14/200517504.NET Framework: 19. VS.NET 2005 Team Foundation Server 설치오류 - 26204 예외
72정성태12/26/200418950.NET Framework: 18. .NET Framework 2.0 Beta 설치 후에 Windows SharePoint Service 오류 [1]
136정성태3/31/200518824    답변글 .NET Framework: 18.1. Windows Sharepoint Services 를 설치한 이후 ASP.NET 오류 문제
71정성태12/26/200417176VS.NET IDE: 11. SQL Server 2005 Beta 2 를 네트워크 드라이브로부터 설치시 오류
70정성태12/26/200420010VS.NET IDE: 10. WSS 설치 후 localhost 접근 보안 오류
69정성태12/5/200417089VS.NET IDE: 9. 다른 컴퓨터(방화벽 설치)에 설치된 SQL Server에 통합 인증을 할 때 필요한 포트
... 181  182  183  184  185  186  187  188  189  190  191  192  193  [194]  195  ...