WaitForMultipleObjects等待多个事件对象

来源:互联网 发布:怎么删除网络绯闻 编辑:程序博客网 时间:2024/06/05 05:22

函数原型:

DWORD WaitForMultipleObjects(
  DWORD
nCount,            // number of handles in array
  CONST HANDLE *lpHandles // object-handlearray
  BOOL fWaitAll,           // wait option
  DWORD dwMilliseconds     // time-out interval
);

 该函数功能强大,几乎可以处理Windows下的所有事件,但在处理多个事件对象时,比较容易出错。

MSDN:

  The function modifies the state of some typesof synchronization objects. Modification occurs only for the objector objects whose signaled state caused the function to return. Forexample, the count of a semaphore object is decreased by one. WhenfWaitAll is FALSE, and multiple objects are in the signaledstate, the function chooses one of the objects to satisfythe wait; the states of the objects not selected areunaffected.

问题:

当fWaitAll变量赋值FALSE时,若有多个对象在dwMilliseconds内同时响应,则函数只返回其中一个对象(通常是数组lpHandles中序号最小的)并修改其状态,而不改变其它对象的状态。这将导致序号较小的对象频繁响应,而序号较大的对象得不到处理。本人在coding时,遇到过这种问题。

解决方案:

 可采取循环使用双WaitForMultipleObjects函数处理多对象等待问题。

DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
 DWORD dwRet = 0;
 int nIndex = 0;
 while(1)
 {
  dwRet =WaitForMultipleObjects(nCount,pHandles,false,INFINITE);
  switch(dwRet)
  {
   case WAIT_TIMEOUT:
    break;
   case WAIT_FAILED:
    return 1;
   default:
   {
    nIndex = dwRet -WAIT_OBJECT_0;
    ProcessHanlde(nIndex++);
    //同时检测其他的事件
    while(nIndex <nCount)
    {
     dwRet =WaitForMultipleObjects(nCount -nIndex,&pHandles[nIndex],false,0);
     switch(dwRet)
     {
      caseWAIT_TIMEOUT:
       nIndex= nCount; //退出检测,因为没有被触发的对象了.
       break;
      caseWAIT_FAILED:
       return1;
      default:
      {
       nIndex= dwRet - WAIT_OBJECT_0;
       ProcessHanlde(nIndex++);
      }
      break
     }
    }
   }
   break;
  }
 }
 return 0;
}

原创粉丝点击