大龙的博客

常用链接

统计

最新评论

WaitForMultipleObjects用法探索

WaitForMultipleObjects用法探索
                        

WaitForMultipleObjectsWindows中的一个功能非常强大的函数,几乎可以等待Windows中的所有的内核对象(关于该函数的描述和例子见MSDN,)。但同时该函数在用法上却需要一定的技巧。

原型DWORD WaitForMultipleObjects(
 DWORD nCount,
 const HANDLE* lpHandles,
 BOOL bWaitAll,
 DWORD dwMilliseconds
);

 

WaitForMultipleObjects等到多个内核对象的时候,如果它的bWaitAll 参数设置为false。其返回值减去WAIT_OBJECT_0 就是参数lpHandles数组的序号。如果同时有多个内核对象被出发,这个函数返回的只是其中序号最小的那个。

问题就在这里,我们如何可以获取所有被同时触发的内核对象。举个例子:我们需要在一个线程中处理从完成端口、数据库、和可等待定时器来的数据。一个典型的实现方法就是:用WaitForMultipleObjects等待所有的这些事件。如果完成端口,数据库发过来的数据量非常大,可等待定时器时间也只有几十毫秒。那么这些事件同时触发的几率可以说非常大,我们不希望丢弃任何一个被触发的事件。那么如何能高效地实现这一处理呢?

MSDN中有一句非常重要的描述,它可以说是WaitForMultipleObjects用法的精髓: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 bWaitAll 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.

多个内核对象被触发时,WaitForMultipleObjects选择其中序号最小的返回。而WaitForMultipleObjects它只会改变使它返回的那个内核对象的状态。

这儿又会产生一个问题,如果序号最小的那个对象频繁被触发,那么序号比它大的内核对象将的不到被出理的机会。

为了解决这一问题,可以采用双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;

}

posted on 2007-12-02 18:57 大龙 阅读(16332) 评论(3)  编辑 收藏 引用

评论

# re: WaitForMultipleObjects用法探索 2009-02-19 12:01 Rs

学习  回复  更多评论   

# re: WaitForMultipleObjects用法探索 2009-12-29 09:48 asdfa

错误  回复  更多评论   

# re: WaitForMultipleObjects用法探索 2012-05-09 11:40 皋涵

好文章  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理