Windows API函数 WaitForMultiObjects 的使用注意事项

今天在使用CreateThread 和


WaitForMultiObjects 来创建和回收线程的时候,发生了错误。


当线程数是小于64的时候,没有问题,当线程数大于64的时候,出现问题。


原因是  WaitForMultiObjects(...) 最多只能等待MAXIMUM_WAIT_OBJECTS个kernal objects。MAXIMUM_WAIT_OBJECTS被定义为64。那么这就限制了一次最多只能等待64个内核对象。

如果线程数超过64个,那么就会出现错误。


下面是一种编程的方法(来自网络):

#include <Windows.h>

/*
* Synchronically waiting for all objects signaled.
* - handles : An array of object handles to wait.
* - count   : The count of handles.
* returns : Same as WaitForMultipleObjects.
*/
DWORD SyncWaitForMultipleObjs(HANDLE * handles, size_t count)
{
    int waitingThreadsCount = count;
    int index = 0;
    DWORD res = 0;
    while(waitingThreadsCount >= MAXIMUM_WAIT_OBJECTS)
    {
        res = WaitForMultipleObjects(MAXIMUM_WAIT_OBJECTS, &handles[index], TRUE, INFINITE);
        if(res == WAIT_TIMEOUT || res == WAIT_FAILED)
        {
            puts("1. Wait Failed.");
            return res;
        }

        waitingThreadsCount -= MAXIMUM_WAIT_OBJECTS;
        index += MAXIMUM_WAIT_OBJECTS;
    }

    if(waitingThreadsCount > 0)
    {
        res = WaitForMultipleObjects(waitingThreadsCount, &handles[index], TRUE, INFINITE);
        if(res == WAIT_TIMEOUT || res == WAIT_FAILED)
        {
            puts("2. Wait Failed.");
        }
    }

    return res;
}




你可能感兴趣的:(C++,windows)