WaitForMultipleObjects等待多个事件对象

本文详细介绍了如何通过循环调用WaitForMultipleObjects函数来解决Windows下多个事件对象等待时的问题。重点阐述了在fWaitAll为FALSE时,如何确保每个对象都有机会被处理,避免了序号较小的对象频繁响应而序号较大对象得不到处理的情况。通过实例代码展示了实现步骤,并提供了关键代码段的解释。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数原型:

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值