Microsoft MVP성태의 닷넷 이야기
.NET Framework: 610. C# - WaitOnAddress Win32 API 사용 [링크 복사], [링크+제목 복사],
조회: 14440
글쓴 사람
정성태 (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)
11190정성태5/2/201721169Windows: 138. Windows 운영체제의 ISO 설치 파일에 미리 Device driver를 준비하는 방법
11189정성태5/2/201713874Windows: 137. Windows 7 USB/DVD DOWNLOAD TOOL로 98%에서 실패하는 경우
11188정성태4/27/201715599VC++: 118. Win32 HANDLE 자료형의 이모저모
11187정성태4/26/201716395개발 환경 구성: 314. C# - PowerPoint 확장 Add-in 만드는 방법 [1]파일 다운로드1
11186정성태4/24/201714294VS.NET IDE: 117. Visual Studio 확장(VSIX)을 이용해 사용자 매크로를 추가하는 방법 [1]파일 다운로드1
11185정성태4/22/201712785VS.NET IDE: 116. Visual Studio 확장(VSIX)을 이용해 사용자 메뉴 추가하는 방법 (2) - 동적 메뉴 구성파일 다운로드1
11184정성태4/21/201714025VS.NET IDE: 115. Visual Studio 확장(VSIX)을 이용해 사용자 메뉴 추가하는 방법파일 다운로드1
11183정성태4/19/201712530.NET Framework: 654. UWP 앱에서 FolderPicker 사용 시 유의 사항파일 다운로드1
11182정성태4/19/201716473개발 환경 구성: 313. Nuget Facebook 라이브러리를 이용해 ASP.NET 웹 폼과 로그인 연동하는 방법
11181정성태4/18/201713120개발 환경 구성: 312. Azure Web Role의 AppPool 실행 권한을 Local System으로 바꾸는 방법
11180정성태4/16/201715071Java: 18. Java의 Memory Mapped File 자원 반환이 안되는 문제
11179정성태4/13/201710215기타: 64. SVG Converter 스토어 앱 개인정보 보호 정책 안내
11178정성태4/10/201711963개발 환경 구성: 311. COM+ 관리자의 DCOM 구성에 나오는 기준
11177정성태4/7/201712759.NET Framework: 653. C# 7 새로운 문법(1) - 더욱 편리해진 Out 변수 사용파일 다운로드1
11176정성태4/5/20179908VC++: 117. Visual Studio - ATL COM 개체를 단위 테스트 하는 방법
11175정성태4/5/201719290.NET Framework: 652. C# 개발자를 위한 C++ COM 객체의 기본 구현 방식 설명파일 다운로드1
11174정성태4/3/201712911VC++: 116. Visual Studio 단위 테스트 - Failed to set up the execution context to run the test
11173정성태4/3/201716487VC++: 115. Visual Studio에서 C++ DLL을 대상으로 단위 테스트할 때 비정상 종료한다면?파일 다운로드1
11172정성태4/3/201715713.NET Framework: 651. C# - 특정 EXE 프로세스를 종료시킨 EXE를 찾아내는 방법파일 다운로드1
11171정성태3/31/201712482VS.NET IDE: 114. Visual Studio 디버깅 경고 창 - You are debugging a Release build of ...
11170정성태3/31/201713746.NET Framework: 650. C# - CachedAnonymousMethodDelegate 유형의 코드 생성
11169정성태3/30/201713792VC++: 114. C++ vtable의 가상 함수 호출 가로채기파일 다운로드1
11168정성태3/29/201717482VC++: 113. C++ 클래스 상속 관계의 vtable 생성 과정
11167정성태3/28/201717647VC++: 112. C++의 가상 함수 테이블 (vtable)은 언제 생성될까요? [2]
11166정성태3/28/201711735오류 유형: 382. System.Data.SqlClient.SqlException - Arithmetic overflow error converting IDENTITY to data type int.
11165정성태3/27/201715333오류 유형: 381. Visual C++에서 min, max 함수를 사용한 경우 C2589, C2059 컴파일 오류 발생
... 91  92  93  94  95  96  97  [98]  99  100  101  102  103  104  105  ...