您的位置:首页 > 移动开发 > Objective-C

WaitForMultipleObjects等待多个事件对象

2011-06-28 10:34 519 查看
函数原型:

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐