Microsoft MVP성태의 닷넷 이야기
.NET Framework: 610. C# - WaitOnAddress Win32 API 사용 [링크 복사], [링크+제목 복사]
조회: 13882
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12371정성태10/13/20209851개발 환경 구성: 519. Visual Studio의 Ctrl+Shift+U (Edit.MakeUppercase) 단축키가 동작하지 않는 경우
12370정성태10/13/202010699Linux: 33. Linux - nmcli를 이용한 고정 IP 설정
12369정성태10/12/202013529Windows: 176. Raymond Chen이 한글날에 밝히는 윈도우의 한글 자모 분리 현상 [3]
12368정성태10/12/20209555오류 유형: 668. VSIX 확장 빌드 - The "GetDeploymentPathFromVsixManifest" task failed unexpectedly.
12367정성태10/12/202022256오류 유형: 667. Ubuntu - Temporary failure resolving 'kr.archive.ubuntu.com' [2]
12366정성태10/12/202011339.NET Framework: 950. C# 9.0 - (4) 원시 크기 정수(Native ints) [1]파일 다운로드1
12365정성태10/12/202010321.NET Framework: 949. C# 9.0 - (3) 람다 메서드의 매개 변수 무시(Lambda discard parameters)파일 다운로드1
12364정성태10/11/202011534.NET Framework: 948. C# 9.0 - (2) localsinit 플래그 내보내기 무시(Suppress emitting localsinit flag)파일 다운로드1
12363정성태10/11/202012423.NET Framework: 947. C# 9.0 - (1) 대상으로 형식화된 new 식(Target-typed new expressions) [2]파일 다운로드1
12362정성태10/11/20209188VS.NET IDE: 151. Visual Studio 2019에 .NET 5 rc/preview 적용하는 방법
12361정성태10/11/202010784.NET Framework: 946. C# 9.0을 위한 개발 환경 구성
12360정성태10/8/20208043오류 유형: 666. The type or namespace name '...' does not exist in the namespace 'Microsoft.VisualStudio.TestTools' (are you missing an assembly reference?)
12359정성태10/7/20209569오류 유형: 665. Windows - 재부팅 후 iSCSI 연결이 끊기는 문제
12358정성태10/7/20209540오류 유형: 664. Web Deploy 설치 시 "A newer version of Microsoft Web Deploy 3.6 was found on this machine." 오류 [3]
12357정성태10/7/20207653오류 유형: 663. 이벤트 로그 - The storage optimizer couldn't complete retrim on New Volume
12356정성태10/7/202022272오류 유형: 662. ASP.NET Core와 500.19, 500.21 오류 (0x8007000d)
12355정성태10/3/20207726오류 유형: 661. Hyper-V Linux VM의 Internal 유형의 가상 Switch에 대한 IP 연결이 되지 않는 경우
12354정성태10/2/202020521오류 유형: 660. Web Deploy (msdeploy.axd) 실행 시 오류 기록 [1]
12353정성태10/2/202010343개발 환경 구성: 518. 비주얼 스튜디오에서 IIS 웹 서버로 "Web Deploy"를 이용해 배포하는 방법
12352정성태10/2/202010857개발 환경 구성: 517. Hyper-V Internal 네트워크에 NAT을 이용한 인터넷 연결 제공
12351정성태10/2/202010350오류 유형: 659. Nox 실행이 안 되는 경우 - Unable to bind to the underlying transport for ...
12350정성태9/25/202013862Windows: 175. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 [2]파일 다운로드1
12349정성태9/25/20208840Linux: 32. Ubuntu 20.04 - docker를 위한 tcp 바인딩 추가
12348정성태9/25/20209566오류 유형: 658. 리눅스 docker - Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock
12347정성태9/25/202023682Windows: 174. WSL 2의 네트워크 통신 방법 [4]
12346정성태9/25/20208820오류 유형: 657. IIS - http://localhost 방문 시 Service Unavailable 503 오류 발생
... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...