APC异步调用过程二

转自:http://blog.sina.com.cn/s/blog_6c617ee301017nhr.html

2014-08-28 17:15:52

 

apc可以看成就是内核里的定时器,为了给自己一个在本函数返回后还能执行的一次机会,有很多操作是需要在函数返回后才能执行.
类似于析构函数但不完全是。
apc的最大特点就是在本函数返回后才执行,而且是在本线程中。
而内核提供的原生的定时器,执行的环境可能就不是原始的线程了。
windows天生就是个异步框架,里面大量的设计都是为异步而设计,比如IRP,就是贯穿整个windows的异步框架
apc它的执行时机有多,比如在线程wait、线程切换到应用层、线程被挂起等等等等,而且apc也分几个层次的优先级.就是说apc一般是不太需要立马执行的低优先级的函数。所以一旦线程有空隙了,windows就会执行一下
windows在执行完线程的主要任务何后,顺便把apc队列执行一遍
 
一:皮毛
每个线程都会维护一个线程apc队列,通过 QueueUserAPC把一个apc函数添加到指定线程的apc队列
DWORD WINAPI QueueUserAPC(
  _In_  PAPCFUNC pfnAPC,
  _In_  HANDLE hThread,
  _In_  ULONG_PTR dwData
);
 
VOID CALLBACK APCProc(
  _In_  ULONG_PTR dwParam
);
 
Each thread has its own APC queue. The queuing of an APC is a request for the thread to call the APC function. The operating system issues a software interrupt to direct the thread to call the APC function.
每个线程都由她自己的APC队列,这个APC队列纪录了要求线程去执行的一些APC函数。OS发出一个软中断去执行这些APC函数。
 
When a user-mode APC is queued, the thread is not directed to call the APC function unless it is in an alertable state.
对于用户模式下是APC队列,当线程处在alertable状态时才去执行这些APC函数。
 
 A thread enters an alertable state by using SleepEx, SignalObjectAndWait, WaitForSingleObjectEx, WaitForMultipleObjectsEx, or MsgWaitForMultipleObjectsEx to perform an alertable wait operation.
一个线程内部使用SleepEx, SignalObjectAndWait, WaitForSingleObjectEx, WaitForMultipleObjectsEx, or MsgWaitForMultipleObjectsEx 等函数把自己挂起时就是进入alertable状态,此时执行APC队列的函数。
*Ex(..,TRUE)最后一个参数为TRUE才进入alertable状态,不带Ex的这些函数默认FALSE掉用相应的*Ex不进入alertable状态。
 
After the thread is in an alertable state, the thread handles all pending APCs in first in, first out (FIFO) order, and the wait operation returns WAIT_IO_COMPLETION. 
线程在alertable状态时按先进先出执行apc,
线程等待的内核对象触发后相应*Ex函数返回值为WAIT_IO_COMPLETION,线程被激活。
If an application queues an APC before the thread begins running, the thread begins by calling the APC function. After the thread calls an APC function, it calls the APC functions for all APCs in its APC queue.(没看明白)
 
When the thread is terminated using the ExitThread or TerminateThread function, the APCs in its APC queue are lost. The APC functions are not called.
 
It is possible to sleep or wait for an object within the APC.(在apc之内去sleep或wait一个对象是可以的)
 
 If you perform an alertable wait inside an APC, it will recursively dispatch the APCs. This can cause a stack overflow.(如果你在APC里执行一个alertable,他将按APC路径递归。这可能引起堆栈溢出)
 
 
二:apc过程分析
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <process.h>
using namespace std;
VOID WINAPI APCFunc(ULONG_PTR dwParam)
{
    cout<<"APCFunc:处理APC函数ing"<<endl;
 Sleep(2000);
 cout<<"APCFunc:Sleep了2000,处理APC函数ing"<<endl;
}
VOID WINAPI APCFunc2(ULONG_PTR dwParam)
{
    cout<<"APCFunc2:处理APC函数2ing"<<endl;
 Sleep(100);
 cout<<"APCFunc2:处理APC函数2ing"<<endl;
 
}
DWORD WINAPI ThreadFun(PVOID pvParam)
{
    HANDLE hEvent  = (HANDLE)pvParam;
 Sleep(100);
 cout<<"ThreadFun:WaitForSingleObjectEx(hEvent,INFINITE,TRUE);"<<endl;
    DWORD dw = WaitForSingleObjectEx(hEvent,INFINITE,TRUE);
//*Ex函数把线程设置为alertable状态
    if(dw == WAIT_OBJECT_0)
    {
        cout<<"ThreadFun:事件触发"<<endl;
    }
    if(dw == WAIT_IO_COMPLETION)
    {
        //如果线程至少处理了APC队列中的一项
        cout<<"ThreadFun:APC队列中APC函数执行完,等待函数返回WAIT_IO_COMPLETION激活该线程继续执行"<<endl;
       
    }
    return 0;
}
int main(int argc, char* argv[])
{
 HANDLE hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
 HANDLE hThread = (HANDLE)_beginthreadex(NULL,0,(unsigned int (__stdcall *)(void *))ThreadFun,(PVOID)hEvent,0,NULL);
 //执行一些其他代码
 cout<<"main:开始"<<endl;
 //此时用户想要终止子线程
 Sleep(1000); //留出时间先让子线程进入alertable状态。
 cout<<"main:主程Sleep(1000)此时线程调用WaitForSingleObjectEx处于alertable状态"<<endl;
 QueueUserAPC(APCFunc,hThread,NULL);
 cout<<"main:QueueUserAPC(APCFunc,hThread,NULL);"<<endl;
 Sleep(1500);
 cout<<"main:主程Sleep了1500时间比APCFunc的2000短,让线程在执行完APC函数前往其中添加新的APCFunc2"<<endl;
 QueueUserAPC(APCFunc2,hThread,NULL);
 cout<<"QueueUserAPC(APCFunc2,hThread,NULL);"<<endl;
 WaitForSingleObject(hThread,INFINITE);
 cout<<"main:WaitForSingleObject(hThread,INFINITE);"<<endl;
 system("pause");
 return 0;
}
异步过程调用(APC)



main()在Sleep(1000); 的时候确保新线程调WaitForSingleObjectEx进入alertable状态以执行APC函数。应为返回dw的不是WAIT_OBJECT_0所以不是hEvent被激活触发,而是APC队列中函数执行完毕触发的。
 

异步过程调用(APC)
 
 
 

WaitForSingleObjectEx函数原型如下

DWORD WINAPI WaitForSingleObjectEx(
  __in  HANDLE hHandle,
  __in  DWORD dwMilliseconds,
  __in  BOOL bAlertable
);

 


在SDK6.1文档中,对参数dwMilliseconds说明如下:

The time-out interval, in milliseconds. The function returns if the interval elapses, even if the object's state is nonsignaled and no completion routines or APCs are queued.If dwMilliseconds is zero, the function tests the object's state and checks for queued completion routines or APCs and then returns immediately. IfdwMilliseconds is INFINITE, the function's time-out interval never elapses.

我对其中标红语句的理解是,如何超过时间间隔,即使(even if)对象信号未被触发并且没有完成例程或者APC例程排队。我觉得比较难翻译及理解。于是我又查了下网上MSDN,对参数dwMilliseconds说明如下:

The time-out interval, in milliseconds. If a nonzero value is specified, the function waits until the object is signaled, an I/O completion routine or APC is queued, or the interval elapses. IfdwMilliseconds is zero, the function does not enter a wait state if the criteria is not met; it always returns immediately. IfdwMillisecondsis INFINITE, the function will return only when the object is signaled or an I/O completion routine or APC is queued.

还是没有搞清楚若超过时间间隔,但是当前有完成例程或者APC例程,函数是否返回,于是写了个小Demo测试了一下

#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;

VOID NTAPI ApcFun(__in ULONG_PTR Parameter)
{
    cout<<"ApcFun Running."<<endl;
    Sleep(10000);
}

int _tmain(int argc, _TCHAR* argv[])
{
    HANDLE hEvent=CreateEvent(NULL,FALSE,FALSE,_T(""));

    DWORD dwRet=QueueUserAPC(ApcFun,GetCurrentThread(),NULL);
    cout<<dwRet<<endl;
    dwRet=QueueUserAPC(ApcFun,GetCurrentThread(),NULL);
    cout<<dwRet<<endl;
    dwRet=WaitForSingleObjectEx(hEvent,1000,TRUE);
    cout<<dwRet<<endl;

    CloseHandle(hEvent);
    return 0;
}

 

测试结果是即使超时时间已到,若当前存在完成例程或者APC例程,会把所有的例程执行完毕后才会返回。

如果WaitForSingleObjectEx第3个参数为TRUE,那么WaitForSingleObjectEx在执行时发现存在APC例程需要执行,则当前等待线程执行APC过程,执行完毕后,

不管同步对象是否有信号或者是否超时,函数返回,返回值为WAIT_IO_COMPLETION。

            我写个小demo供测试

#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;

HANDLE hEvent;

DWORD WINAPI ThreadFun(LPVOID lpThreadParameter)
{
    hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);
    DWORD dwRet=WaitForSingleObjectEx(hEvent,INFINITE,TRUE);
    CloseHandle(hEvent);
    return 0;
}

VOID NTAPI UserApc(ULONG_PTR Parameter)
{
    for (int i=0;i<10000;i++)
    {
        for (int j=0;j<10000;j++)
        {
        }
        cout<<i<<endl;
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    HANDLE hThread=CreateThread(NULL,NULL,ThreadFun,NULL,NULL,NULL);
    Sleep(500);
    DWORD dwRet=QueueUserAPC(UserApc,hThread,NULL);
    SetEvent(hEvent);
    WaitForSingleObject(hThread,INFINITE);
    return 0;
}

 

 
在主函数中Sleep(500)的意思是使子线程初始化完毕并且线程函数ThreadFun能够运行起来,若没有这一句,有很大的可能

QueueUserAPC执行完毕后子线程还在初始化中,此时若发现APC队列中存在APC例程,则会先执行apc队列,然后再执行

线程函数,这样会造成WaitForSingleObjectEx执行是apc队列是空的,达不到测试的目的,

就算APC执行过程中同步对象已然有信号,WaitForSingleObjectEx已然会返回WAIT_IO_COMPLETION

posted @ 2014-08-28 17:20  felove  阅读(712)  评论(0)    收藏  举报