Microsoft MVP성태의 닷넷 이야기
.NET Framework: 610. C# - WaitOnAddress Win32 API 사용 [링크 복사], [링크+제목 복사],
조회: 14439
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

C# - WaitOnAddress Win32 API 사용

Windows 8부터 새로 생긴 Win32 API 중에 WaitOnAddress를 살펴보겠습니다.

WaitOnAddress function
; https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitonaddress

이 함수를 사용하는 간단한 코드를 C++로 만들어 보면 다음과 같습니다.

#include "stdafx.h"
#include <synchapi.h>
#include <thread>

#pragma comment(lib, "Synchronization.lib")

int main()
{
    int age = 5;
    int ageCompare = 5;

    char tmpbuf[128];

    int *pAge = &age;
    int *pCompareAge = &ageCompare;

    std::thread t([&]() {
        Sleep(3000);
        *pAge = 6;
        WakeByAddressSingle(pAge);
    });

    _strtime_s(tmpbuf, 128);
    printf("%s Wait on\n", tmpbuf);

    BOOL result = WaitOnAddress(pAge, (PVOID)pCompareAge, 4, -1);

    _strtime_s(tmpbuf, 128);
    printf("%s waited: %d\n", tmpbuf, result);

    t.detach();

    return 0;
}

WaitOnAddress API를 호출하면 처음 2개의 포인터가 가리키는 값을 비교해 같으면 blocking 상태에 빠지고 다르면 곧바로 리턴합니다. 그리고 blocking 상태에 빠진 스레드를 다시 재개하려면 다른 스레드에서 WaitOnAddress의 첫 번째 인자로 넘겨준 주소 값을 WakeByAddressSingle API에 전달해 호출해야 합니다.

문서 상으로 보면 WaitOnAddress는 값이 달라질 때까지 기다린다고 하지만 '값이 다르다는 조건'은 WaitOnAddress 호출 시에만 적용될 뿐 이후에는 그에 상관없이 WakeByAddressSingle, WakeByAddressAll API를 호출하기만 하면 WaitOnAddres 함수가 반환됩니다.

WakeByAddressAll function
; https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-wakebyaddressall

WakeByAddressSingle function
; https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-wakebyaddresssingle

즉, 아래의 "*pAge = 6" 코드를 주석 처리해도 WakeByAddressSingle을 호출했기 때문에 WaitOnAddress의 잠김은 풀리게 됩니다.

std::thread t([&]() {

    Sleep(3000);
    // *pAge = 6;
    WakeByAddressSingle(pAge);
});

이 함수의 의미 및 몇 가지 적용 예제는 Raymond Chen의 블로그에 자세하게 실려 있습니다.

WaitOnAddress lets you create a synchronization object out of any data variable, even a byte
; https://blogs.msdn.microsoft.com/oldnewthing/20160823-00/?p=94145

Implementing a synchronization barrier in terms of WaitOnAddress
; https://blogs.msdn.microsoft.com/oldnewthing/20160824-00/?p=94155

Implementing a critical section in terms of WaitOnAddress
; https://blogs.msdn.microsoft.com/oldnewthing/20160825-00/?p=94165




물론, C#에서도 사용 가능합니다. 다음은 C++의 코드에 대응하는 C# 예제 코드입니다.

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

namespace ConsoleApplication1
{
    class Person
    {
        public int Age;
    }

    unsafe class Program
    {
        [DllImport("kernelbase.dll", SetLastError = true)]
        static extern int WaitOnAddress(int *address, int *compareAddress, int addressSize, int dwMilliseconds);

        [DllImport("kernelbase.dll", SetLastError = true)]
        static extern void WakeByAddressSingle(int * address);

        int AgeComare;

        static void Main(string[] args)
        {
            Person person = new Person();
            person.Age = 5;

            Program pg = new Program();
            pg.AgeComare = 5;

            fixed (int* pCompareAge = &pg.AgeComare)
            fixed (int* pAge = &person.Age)
            {
                Thread t1 = new Thread(changeVarProc);
                t1.Start(new IntPtr(pAge));

                Console.WriteLine(DateTime.Now + " Wait on ");
                int result = WaitOnAddress(pAge, pCompareAge, 4, -1);
                Console.WriteLine(DateTime.Now + " Waited: " + result);
            }
        }

        private static void changeVarProc(object obj)
        {
            IntPtr ptr = (IntPtr)obj;
            int *pAge = (int *)ptr.ToPointer();

            Thread.Sleep(3000);

            // *pAge = 6;

            WakeByAddressSingle(pAge);

            Console.WriteLine("value changed: " + *pAge);
        }
    }
}

(첨부한 파일은 이 글의 소스 코드를 포함합니다.)




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







[최초 등록일: ]
[최종 수정일: 10/19/2019]

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)
11290정성태9/3/201716941개발 환경 구성: 326. 아파치 서버에서 ASP.NET을 실행하는 mod_aspdotnet 모듈 [2]
11289정성태9/3/201714273개발 환경 구성: 325. GAC에 어셈블리 등록을 위해 gacutil.exe을 사용하는 경우 주의 사항
11288정성태9/3/201711956개발 환경 구성: 324. 윈도우용 XAMPP의 아파치 서버 구성 방법
11287정성태9/1/201720803.NET Framework: 680. C# - 작업자(Worker) 스레드와 UI 스레드 [11]
11286정성태8/28/20179049기타: 67. App Privacy Policy
11285정성태8/28/201716911.NET Framework: 679. C# - 개인 키 보안의 SFTP를 이용한 파일 업로드파일 다운로드1
11284정성태8/27/201714829.NET Framework: 678. 데스크톱 윈도우 응용 프로그램에서 UWP 라이브러리를 이용한 비디오 장치 열람하는 방법 [1]파일 다운로드1
11283정성태8/27/201711058오류 유형: 418. CSS3117: @font-face failed cross-origin request. Resource access is restricted.
11282정성태8/26/201713432Math: 22. 행렬로 바라보는 피보나치 수열
11281정성태8/26/201714894.NET Framework: 677. Visual Studio 2017 - NuGet 패키지를 직접 참조하는 PackageReference 지원 [2]
11280정성태8/24/201711825디버깅 기술: 94. windbg - 풀 덤프에 포함된 모든 모듈을 파일로 저장하는 방법
11279정성태8/23/201722992.NET Framework: 676. C# Thread가 Running 상태인지 아는 방법
11278정성태8/23/201711705오류 유형: 417. TFS - Warning - Unable to refresh ... because you have a pending edit. [1]
11277정성태8/23/201713042오류 유형: 416. msbuild - error MSB4062: The "TransformXml" task could not be loaded from the assembly
11276정성태8/23/201716792.NET Framework: 675. C# - (파일) 확장자와 연결된 실행 파일 경로 찾기 [2]파일 다운로드1
11275정성태8/23/201725285개발 환경 구성: 323. Visual Studio 설치 없이 빌드 환경 구성 - Visual Studio 2017용 Build Tools [1]
11274정성태8/22/201712976.NET Framework: 674. Thread 타입의 Suspend/Resume/Join 사용 관련 예외 처리
11273정성태8/22/201715575오류 유형: 415. 윈도우 업데이트 에러 Error 0x80070643
11272정성태8/21/201717158VS.NET IDE: 120. 비주얼 스튜디오 2017 버전 15.3.1 - C# 7.1 공개 [2]
11271정성태8/19/201712777VS.NET IDE: 119. Visual Studio 2017에서 .NET Core 2.0 프로젝트 환경 구성하는 방법
11270정성태8/17/201723238.NET Framework: 673. C#에서 enum을 boxing 없이 int로 변환하기 [2]
11269정성태8/17/201714421디버깅 기술: 93. windbg - 풀 덤프에서 .NET 스레드의 상태를 알아내는 방법
11268정성태8/14/201713771디버깅 기술: 92. windbg - C# Monitor Lock을 획득하고 있는 스레드 찾는 방법
11267정성태8/10/201717561.NET Framework: 672. 모노 개발 환경
11266정성태8/10/201716306.NET Framework: 671. C# 6.0 이상의 소스 코드를 Visual Studio 설치 없이 명령행에서 컴파일하는 방법
11265정성태8/10/201741378기타: 66. 도서: 시작하세요! C# 7.1 프로그래밍: 기본 문법부터 실전 예제까지 [11]
... 91  92  93  [94]  95  96  97  98  99  100  101  102  103  104  105  ...