WaitForMultipleObjects等待多个事件对象

函数原型:

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

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

MSDN:

  The function modifies the state of some types of synchronization objects. Modification occurs only for the object or objects whose signaled state caused the function to return. For example, the count of a semaphore object is decreased by one. When fWaitAll is FALSE, and multiple objects are in the signaled state, the function chooses one of the objects to satisfy the wait; the states of the objects not selected are unaffected.

问题:

当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)
     {
      case WAIT_TIMEOUT:
       nIndex = nCount; //退出检测,因为没有被触发的对象了.
       break;
      case WAIT_FAILED:
       return 1;
      default:
      {
       nIndex = dwRet - WAIT_OBJECT_0;
       ProcessHanlde(nIndex++);
      }
      break
     }
    }
   }
   break;
  }
 }
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值