Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2065. C# - Mutex의 비동기 버전 [링크 복사], [링크+제목 복사]
조회: 5766
글쓴 사람
정성태 (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# - 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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...
NoWriterDateCnt.TitleFile(s)
13297정성태3/26/20234350Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/20233692Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/20233957Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/20234126.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/20234195오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/20234314Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/20234721.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
13290정성태3/19/20234225.NET Framework: 2103. C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법파일 다운로드1
13289정성태3/18/20233419Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법파일 다운로드1
13288정성태3/17/20233519Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법파일 다운로드1
13287정성태3/16/20233688Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
13286정성태3/15/20234147Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
13285정성태3/14/20233741Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법파일 다운로드1
13284정성태3/13/20233942Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법파일 다운로드1
13283정성태3/12/20233482오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
13282정성태3/12/20233819Linux: 58. WSL - nohup 옵션이 필요한 경우
13281정성태3/12/20233720Windows: 225. 윈도우 바탕화면의 아이콘들이 넓게 퍼지는 경우 [2]
13280정성태3/9/20234472개발 환경 구성: 670. WSL 2에서 호스팅 중인 TCP 서버를 외부에서 접근하는 방법
13279정성태3/9/20234013오류 유형: 851. 파이썬 ModuleNotFoundError: No module named '_cffi_backend'
13278정성태3/8/20233973개발 환경 구성: 669. WSL 2의 (init이 아닌) systemd 지원 [1]
13277정성태3/6/20234637개발 환경 구성: 668. 코드 사인용 인증서 신청 및 적용 방법(예: Digicert)
13276정성태3/5/20234316.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어
13275정성태3/3/20234669.NET Framework: 2101. C# 11의 ref 필드 설명
13274정성태3/2/20234260.NET Framework: 2100. C# - ref 필드로 ref struct 타입을 허용하지 않는 이유
13273정성태2/28/20233958.NET Framework: 2099. C# - 관리 포인터로서의 ref 예약어 의미
13272정성태2/27/20234216오류 유형: 850. SSMS - mdf 파일을 Attach 시킬 때 Operating system error 5: "5(Access is denied.)" 에러
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...