您的位置:首页 > 其它

并发学习之:APC (异步过程调用)

2013-01-07 01:01 344 查看
一个简单的APC例子,对应于Windows 并发编程指南p124。

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

VOID NTAPI ApcFunc(ULONG_PTR pValue)
{
printf("Hello, this is APC and the parameter value is %d\n", *((DWORD*)pValue));
delete (DWORD*)pValue;
}

DWORD WINAPI Thread_A_Proc(LPVOID)
{
printf("Thread A is waiting...\n");

// Note: hEvent never signals
HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE/*bInitialState*/, NULL);

// Wait till APC calls
DWORD dwRet = WaitForSingleObjectEx(hEvent, INFINITE, TRUE /*bAlertable*/);
if(dwRet == WAIT_IO_COMPLETION)
printf("Hoho, A is waken up by APC call.\n");

CloseHandle(hEvent);
return 0L;
}

DWORD WINAPI Thread_B_Proc(LPVOID hThread_A)
{
printf("Thread B will wake up Thread A in 3 sec...\n");

Sleep(3000);
DWORD* dwData = new DWORD(2013);
QueueUserAPC(ApcFunc, (HANDLE)hThread_A, (ULONG_PTR)dwData);
return 0L;
}

int wmain(int argc, wchar_t * argv[])
{
HANDLE handles[2] = {};

// 1) Create two thread:
//        A. Sleep and alertable wait.
//        B. Send a APC to A's APC queue.
HANDLE hThread_A = handles[0] = CreateThread(NULL, 0, Thread_A_Proc, NULL, 0, NULL);
HANDLE hThread_B = handles[1] = CreateThread(NULL, 0, Thread_B_Proc, hThread_A, 0, NULL);

WaitForMultipleObjects(2, handles, TRUE, INFINITE);

printf("Done!\n");
getchar();
}


执行结果:

Thread A is waiting...
Thread B will wake up Thread A in 3 sec...
Hello, this is APC and the parameter value is 2013
Hoho, A is waken up by APC call.
Done!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: